Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC 1306 COMPUTER SCIENCE AND PROGRAMMING

Similar presentations


Presentation on theme: "COSC 1306 COMPUTER SCIENCE AND PROGRAMMING"— Presentation transcript:

1 COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Jehan-François Pâris Fall 2017 1

2 THE ONLINE BOOK CHAPTER II BASIC PYTHON

3 Values Python programs manipulate values "Hello world!" "2+3" 5
Values have types

4 Value types (I) >>> type ("Hello world!") <class 'str'>
<class 'int'> >>> type(3.1416) <class 'float'> Strings, integer and floating point are basic Python types

5 Value types (II) >>> type("3.1416") <class 'str'> >>> type('3.1416') >>> Anything between matching quotes is a string

6 Strings Delimited by matching single quotes (' …')
Can contain double quotes (") 'The subject was "touchy", she said' Delimited by matching double quotes (' …') "Let's go!" Delimited by three matching double quotes ("""…""") Can contain almost anything

7 Find the malformed strings
"Hello!" 'I'm busy!' "I like sugar cones.' "He asked for a "petit noir"." """I don't want a "petit noir".""" 'Cookies and cream'

8 Find the malformed strings
"Hello!" 'I'm busy!' single quote inside '…' "I like sugar cones.' mismatched quotes "He asked for a "petit noir"." """I don't want a "petit noir".""" 'Cookies and cream'

9 Integers 0, 1 ,2, 3, … and -1, -2, -3 , … No separating quotes
It is and not 13,000 Can handle really huge large numbers Computations are always exact Nice feature of Python 3

10 Floating-point numbers
0.1, , , … But also .1, .25, .001 You could also meet later 1E3 (for 1 ×103), 1E-3 (for 0.001), … Limited precision Fine for most applications

11 Find the malformed numbers
55,000 0.375 -32 3E3 -.5 3 000

12 Find the malformed numbers
55,000 0.375 -32 3E3 -.5 3 000

13 Numbers and strings '9' and 9 are two different values
'9' means the digit "9" 9 means the number 9 They are not equal You cannot use one instead of the other

14 Converting numbers into strings
>>> str(9) '9' >>> str(3.1416) '3.1416'

15 Converting strings into int
35 >>> int("six") Does not work >>> int("3.1416")

16 Converting strings into float

17 Converting numbers >>> float(3) 3.0 >>> int(3.1416) 3 >>> int(2.90) 2 >>> int(-2.90) -2 Truncates Does not round up

18 Variables Names that refer to a value pi 3.1416

19 Assigning a value name = 'Alice' Value assigned to variable can change
result = 0 result = result = 'undefined'

20 This is Python, not algebra (I)
In Python, Ruby, C, C++, Java, Javascript, … The = sign does not mean equality It means an assignment variable  value When you see shirt_price = 24.99 think of shirt_price  24.99

21 This is Python, not algebra (II)
Why? Using an equal sign for assignments started with FORTRAN in mid fifties Equal sign remains easier to type than left arrow The symbol for equality is the double equal sign a == b

22 Variable names Can consist of multiple characters:
Must be letters, digits and underscore (“_”) Cannot start with a digit Case sensitive Total, total and TOTAL are three different variable names

23 Prohibited variable names
Some possible variable names are already used by Python Keywords Here is the full list and as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass raise return try while with yield True False None

24 Variables have types >>> a = "hello!" >>> type(a) <class 'str'> >>> a = 5 <class 'int'> >>> a = 3.5 <class 'float'> The type of a variable is the type of the value it refers to It can change over time

25 Find the wrong variable names
aleph Fall16 easy_money bigBrother 2step starts with a digit Texas2step raise is a reserved word

26 Find the wrong variable name
aleph Fall16 easy_money bigBrother 2step Texas2step raise

27 Picking good variable names
Using mnemonic names helps making programs more readable by humans instructor_name or instructorName, student__name or instructorName Instead of nm1, nm2 But Python ignores them!

28 Statements and expressions (I)
A statement specifies an action that the Python interpreter can execute print("Hello world!) count = 0 Typically occupies a line Basic element of a program

29 Statements and expressions (II)
An expression is Python's equivalent of an algebraic expression Three differences They are always evaluated They use somewhat different conventions 𝑎2 + 2𝑎𝑏 +𝑏2 becomes a**2 + 2*a*b + b**2 They are more general

30 Statements or expressions?
>>> name = "Mike" >>> print(name) Mike >>> len(name) 4 >>> nameLength = len(name) >>> 13 >>> total =

31 Statements or expressions?
>>> name = "Mike" Statement >>> print(name) Statement Mike >>> len(name) Expression 4 >>> nameLength = len(name) Statement >>> Expression 13 >>> total = Statement

32 Operators and Operands
Most of the operators are the same as those you encountered in HS Algebra but Multiplication sign is * Multiplication is never explicit Must distinguish between max and m*a*x Exponentiation is ** Operators obey the same precedence rules as in HS algebra

33 Examples >>> >>> 1*2*3 6 >>> 25/ >>> 16/2 8.0 In Python the division operator always returns a float

34 Integer division (//) >>> 5//4 1 (and not 1.25)
>>> 8//4 2 (and not 2.0) >>> 6.0//4 1.0 (and not 1.5) >>> 3.5//2 1.0 (and not 1.75)

35 The modulus operator (%)
a%b returns the remainder of the integer division of a by b >>> 9//4 2 >>> 9 - (9//4)*4 1 >>> 9%4

36 The modulus operator (%)
Also work for floating-point numbers >>> 4.6//2 2.0 >>> 4.6%2 Floating-point computation was not accurate but fairly close

37 Our friend the input() function (I)
Specific to Python xyz = input("Blablabla: ") Will print Blablabla:_ Will store in xyz the characters you will enter

38 Our friend the input() function (II)
The value returned by input will always be a string price = enter("Enter a price: ") If you want an int or a float you must convert the string price = float(enter("Enter a price: ")) Note the two closing parentheses

39 Wishing a happy birthday (I)
We want to print a personalized birthday wish Happy birthday Michael User will enter the name of the person Program will do the rest Will also ask the program to prompt the user for a name Enter a name:

40 Wishing a happy birthday (II)
name = input("Enter a name:") print("Happy birthday", name) When you specify several items as the arguments of a print function, print separates them with spaces >>> print ("Hello", "world!") Hello world!

41 The concatenation operator
The same + as for addition "U" + "H" returns "UH" "How" + "are" + you" + "?" returns "Howareyou?" No spaces are added! "How_" + "are_" + you_" + "?" returns "How are you?"

42 Order of operations Consider a*b**2 +c*d/4 – e/f
In which order are the operations performed? In the same order as in algebra First exponentiations right to left Then multiplications and divisions left to right Finally additions and subtractions left to right Parentheses override these priorities

43 Precedence rules ** *, / and // + and -

44 With or without parentheses?
Which expressions are equivalent? a + (b – c) a + b – c (a*b)**2 a*b**2 (a + b)/2 a + b/2 a/(b*c) a/b*c (a*b)/c a*b/c (a**b)**c a**b**c a**(b**c) a**(b**c)

45 The answers Which expressions are equivalent? a + (b – c) a + b – c
(a*b)**2 a*b**2 = a*(b**2) (a + b)/2 a + b/2 = a + (b/2) a/(b*c) a/b*c = (a/b)*c (a*b)/c a*b/c (a**b)**c a**b**c = a**(b**c) a**(b**c) a**b**c

46 My take Know the rules For the quiz
For deciphering complex expressions Use wisely parentheses in your code When it is needed When it clarifies dubious cases (a*b)/c a**(b**c)

47 Remember Nobody ever failed a test because he or she used a few extra parentheses The reverse is not true

48 Reassignment Including variables At the beginning of the season
shirt_price = 24.99 Then discounted shirt_price = 12.99 Finally red-tagged shirt_price = 7.99

49 Updating a variable (I)
Coffeehouse tab Open tab: tab = 0 Add a latte: tab = tab Add sales tax tab = tab *0.0825

50 A short cut Rather than typing tab = tab + 4.95 you can type
It works for +, -, * and / price /= 2

51 Updating a variable revisited
>>> tab = 0 >>> tab >>> tab += 4.95 4.95 >>> tab += 4.95*0.0825 >>>

52 A warning Unlike C, C++, Java, …
Autoincrements (i++, ++i) and autodecrements (i--, --i) are not allowed Cannot use them No i++?

53 Review assignment statement n = n + 1 (means n  n +1)
assignment token = (means ) data type A class of values: int, float, str, …

54 Review expression An algebraic/string expression that produces a result are evaluated to give that result. float Stores floating-point numbers. Only approximate values. initialization (of a variable) To give it an initial value. Essential

55 Review int Holds positive and negative whole numbers. integer division
Yields only the whole number of times that its numerator is divisible by its denominator keyword A word that you cannot use as a variable names

56 Review rules of precedence
Tells in which order expressions are evaluated string Holds a string of characters. type conversion function int(), float(), str().

57 Review value A number or string (or other things to be discussed later) that can be stored in a variable or computed in an expression. variable A name that refers to a value. variable name Must start with a letter (a..z, A..Z, and _) Can contain digits(0..9)


Download ppt "COSC 1306 COMPUTER SCIENCE AND PROGRAMMING"

Similar presentations


Ads by Google