Publish on 03rd November 2019
Category: Birds
0

CS 100: Roadmap toComputingWinter2017-2018Lecture0Python Data Types (I)

Introduction to Computing Using Python

Python Data Types (I)

Expressions, Variables, and AssignmentsIntegersFloatsBooleansStrings

Introduction to Computing Using Python

What this course is about

Thinking algorithmically

Analgorithmis a precise, step-by-step solution to a problem

Designing computational models

Acomputational modelis a simplified description of some piece of theworld,using exactly defineddata typesandactions

A program iswritten in acomputer language(e.g., Python) and implements analgorithm

Writing programs

Introduction to Computing Using Python

Our tools

A computer language (Python)

Instant task: Go to python.org and read aboutthe language, see how to download Python

The Python shell

Instant task: start the Python shell and type in a few expressions

Instant task: open a new window, write some text and save the file

The Python editor

Introduction to Computing Using Python

Computer language v. natural language

Natural language (e.g., English, Arabic, Chinese)

Very many wordsEvolved, not designed. Meaning is derivedbyassociation and usage.Has grammaticalstructure, but very permissive of mistakes, variation and ambiguityMeant for a human being

Very fewwords (a few dozen in Python)Meaning isexact and is assigned by the language designerVery persnickety aboutaccuracy. A single mistake destroys the correctness of a program.Can be executed by aspecial type of machine (a computer)

Programming (computer) language

Introduction to Computing Using Python

Arithmetic data types

Counting type (int)

A type of thing that is discrete and can be countedSimilar to the integer inmathematicsThe value is made up of the digits 0-9 and (optionally) a sign>>>numberOfLittlePigs=3>>>numberOfLittlePigs3>>>type(numberOfLittlePigs)class<'int'>

Canhave anon-unitvalueSimilar to(but not exactly the same as) a decimal numberinmathematicsThe value is made up ofthedigits0-9, a decimal pointand(optionally) a sign>>>pi =3.14159>>>type(pi)class<'float'>

Floating-point arithmetic type

Introduction to Computing Using Python

Arithmetic expressions

>>> 2 + 35>>> 7 - 52>>> 2*(3+1)8>>> 5/22.5>>> 5//22>>> 14//34>>> 14%32>>> 2**38>>> abs(-3.2)3.2>>> min(23,41,15,24)15>>> max(23,41,15,24)41

The Pythoninteractive shell can be usedto evaluate arithmetic expressions

14//3is the quotient when14is divided by3and14%3is the remainder. Note: // is integer division.

2**3is2to the power3

abs(),min(), andmax()arefunctionsabs()takes a number as input and returns its absolute (unsigned) valuemin()(resp.,max()) takes an arbitrary number of inputs and return the “smallest” (“largest”) among them

Introduction to Computing Using Python

Boolean (logical,T/F) data type

In addition to algebraic expressions,Python can evaluate Boolean (T/F) expressionsA Boolean expressionevaluates toTrueorFalseBoolean expressions often involve comparison operators<,>,==,!=,<=, and>=

>>> 2 < 3True>>> 2 > 3False>>> 2 == 3False>>> 2 != 3True>>> 2 <= 3True>>> 2 >= 3False>>> 2+4 == 2*(9/3)True

In an expression containing arithmetic and comparison operators:Arithmetic operators are evaluated firstComparison operators are evaluated next

Introduction to Computing Using Python

Boolean operators

Python can evaluate more complex Boolean expressionsEvery Boolean expressionevaluates toTrueorFalseBoolean expressions may be combined using Boolean operatorsand,or, andnot

>>> 2<3 and 3<4True>>> 4==5 and 3<4False>>> False and TrueFalse>>> True and TrueTrue>>> 4==5 or 3<4True>>> False or TrueTrue>>> False or FalseFalse>>> not(3<4)False>>>not(True)False>>>not(False)True>>> 4+1==5 or 4-1<4True

In a an expression containing algebraic,comparison, and Boolean operators:Algebraic operators are evaluated firstComparison operators are evaluated nextBoolean operators are evaluated last

Introduction to Computing Using Python

Exercise

>>> 25 - 214>>> 14.99 + 27.95 + 19.8362.769999999999996>>> 20*15300>>> 2**101024>>> min(3,1,8,-2,5,-3,0)-3>>> 3 == 4-2False>>> 17//5 == 3True>>> 17%5 == 3False>>> 284%2 == 0True>>> 284%2 == 0 and 284%3 == 0False>>> 284%2 == 0 or 284%3 == 0True

Translate the following into Python algebraic or Boolean expressions and then evaluate them:The difference between Annie’s age (25) and Ellie’s (21)The total of $14.99, $27.95, and $19.83The area of a 20 x 15 rectangle2 to the 10thpowerThe minimum of 3, 1, 8, -2, 5, -3, and 03 equals 4-2The value of 17//5 is 3The value of 17%5 is 3284 is even284 is even and 284 is divisible by 3284 is even or 284 is divisible by 3

Introduction to Computing Using Python

Variables and assignments

<variable> = <expression>

Just as in algebra, a value can be assignedto a variable (name), such asx

When variablexappears inside an expression, it evaluates to its assigned value

A variable (name) does not exist until it is assigned

The assignment statement has the format<expression>is evaluated first, and the resulting value is assigned to variable<variable>

>>>x= 3>>>x3>>> 4*x16>>>yTraceback(most recent call last):File "<pyshell#59>", line 1, in <module>yNameError: name 'y' is not defined>>>y= 4*x>>>y16.0

Introduction to Computing Using Python

Naming rules

(Variable) names can contain thesecharacters:athroughzAthroughZthe underscore character_digits0through9

Names cannot start with a digit. Names canstart with a capital letter or underscore, butdon't do it.

For a multiple-word name, useeither the underscore as the delimiterorcamelCasecapitalization

Meaningful names are important. They makeyour program more readable by a humanbeing (such as you).

>>> my_x2 = 21>>> my_x221>>> 2x = 22SyntaxError: invalid syntax>>>new_temp= 23>>>newTemp= 23>>> counter = 0>>> temp = 1>>> price = 2>>> age = 3

"Hello, World!"

Introduction to Computing Using Python

Text data type (string)

In addition to number and Boolean values, Python support string values

A string value is represented as a sequence of characters enclosed within single or doublequotes

'Hello, World!'

A string value can be assigned to a variable

String values can be manipulated usingstring operators and functions

>>> 'Hello, World!''Hello, World!'>>> s = 'rock'>>> t = 'climbing'>>>s + ' ' + t>>> rock climbing

Introduction to Computing Using Python

String operators

>>> s = 'rock'>>>t= 'climbing'>>>s== 'rock'True>>>s!=tTrue>>> s < t #explain this answer!False>>>s>tTrue>>>s+t'rockclimbing'>>>s+ ' ' +t'rock climbing'>>> 5 *s'rockrockrockrockrock'>>> 20 * '_''____________________'>>> 'o' insTrue>>> 'o' intFalse>>> 'bi' intTrue>>>len(t)8

>>help(str)Help on classstrin modulebuiltins:classstr(object)|str(string[, encoding[, errors]]) ->str...

To view alloperators, use thehelp()tool

Introduction to Computing Using Python

Exercise

Write Python expressions that create stringss1 ('good'),s2 ('bad'), ands3('silly')that correspond to:'ll'appears ins3the blank space does not appear ins1the concatenation ofs1,s2, ands3the blank space appears in the concatenation ofs1,s2, ands3the concatenation of 10 copies ofs3the total number of characters in the concatenation ofs1,s2, ands3

>>> s1'good'>>> s2'bad'>>> s3'silly'>>> 'll' in s3True>>> ' ' not in s1True>>> s1 + s2 + s3'goodbadsilly’>>> ' ' in s1 + s2 + s3False>>> 10*s3'sillysillysillysillysillysillysillysillysillysilly'>>> len(s1+s2+s3)12>>>

Introduction to Computing Using Python

Index and indexing operator

'A'

'p'

'p'

'l'

'e'

s[0]

s[1]

s[2]

s[3]

s[4]

s=

0

1

3

4

2

The index of an item in a sequence is its position with respect to the first itemThe first item has index 0The second has index 1The third has index 2 …

The indexing operator[]takes a indexiand returns a substring consisting of the single character at indexi

>>>s= 'Apple'>>> s[0]'A'>>> s[1]'p'>>> s[4]'e'

'Apple'

Introduction to Computing Using Python

Negative index

'A'

'l'

'e'

s[-1]

s[-2]

s[-5]

s=

0

1

3

4

2

'Apple'

A negative index is used to specify a position with respect to the “end”The last item has index -1The second to last item has index -2The third to last item has index -3 …

-5

-4

-2

-1

-3

>>>s= 'Apple'>>> s[-1]'e'>>> s[-2]'l'>>> s[-5]'A'

Introduction to Computing Using Python

Exercise

Stringsis defined to be'abcdefgh'Write expressions usingsand the indexing operator[]that return the following strings:'a''c''h''f'

>>> s = 'abcdefgh'>>> s[0]'a'>>> s[2]'c'>>> s[7]'h'>>> s[-1]'h'>>> s[-3]'f'>>>

0

Embed

Upload

cs100_lecture_00