Successfully reported this slideshow.
Upcoming SlideShare
×

# Lecture 4 variables data types and operators

504 views

Published on

Published in: Technology
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

### Lecture 4 variables data types and operators

1. 1. 1 of 77Module 4 : Variables, Data types, and OperatorsIntroduction to       Computational ThinkingModule 4 :                                     Variables, Data types, and OperatorsAsst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104email: cwfu[at]ntu.edu.sg
2. 2. 2 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
3. 3. 3 of 77Module 4 : Variables, Data types, and OperatorsWhat is a Variable?• In most computer programs, we need datastorage to represent and store “something”(data) temporarily in programsThis is like M+ andMR in calculator
4. 4. 4 of 77Module 4 : Variables, Data types, and OperatorsWhat is a Variable?• We can use names to make our programmore readable, so that the “something” iseasily understood, e.g., radiusFloatVariable radiusFloat
5. 5. 5 of 77Module 4 : Variables, Data types, and OperatorsVariable Objects• For each variable, Python keeps a pair of info.:• variable’s name• variable’s value• A variable is created when a value is assignedto it for the first time. It associates a name witha value.• We say name references valueName ValueX 7.1X = 7.1
6. 6. 6 of 77Module 4 : Variables, Data types, and OperatorsVariable Objects• Operations: Once a variable is created, wecan store, retrieve, or modify the valueassociated with the variable name• Subsequent assignments can update theassociated valueName ValueX 3.14X = 3.14Name ValueX 5.16X = 5.16
7. 7. 7 of 77Module 4 : Variables, Data types, and OperatorsNamespace• A namespace is the table that contains (andkeeps track of) the association of names withvalues• We will see more about namespaces as we getfurther into Python, but it is an essential part ofthe language.
8. 8. 8 of 77Module 4 : Variables, Data types, and OperatorsNamespace
9. 9. 9 of 77Module 4 : Variables, Data types, and OperatorsNamespace
10. 10. 10 of 77Module 4 : Variables, Data types, and OperatorsPython Naming Conventions• How to name variables?(as well as other things that you will see later inthis course, e.g., user-defined functions, etc.)One basic practice!!!Chooses the names of the variables carefully andexplains what each variable means
11. 11. 11 of 77Module 4 : Variables, Data types, and OperatorsPython Naming ConventionsVSSame program!!!Though both programs work…Different names for the variablesReadability counts!!!What is c?Not immediately clear
12. 12. 12 of 77Module 4 : Variables, Data types, and OperatorsPython Naming ConventionsSyntax rules in Python:• must begin with a letter or _Ab123 and _b123 are OK, but 123ABC is not.• may contain letters, digits, and underscoresthis_is_an_identifier_123• may be of any length• upper and lower case letters are differentLengthOfRope is not lengthofrope• names starting with _ have special meaning.Be careful!!!Python iscase sensitive!!
13. 13. 13 of 77Module 4 : Variables, Data types, and OperatorsA Common Pitfall in PythonCan we interpret and run this program?But what’s wrong?English scores are all 60Hint: a typo!
14. 14. 14 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
15. 15. 15 of 77Module 4 : Variables, Data types, and OperatorsAssignment Operator• As mentioned in previous moduleThe = sign is the assignment operator but notthe equality in mathematics• So, when we seea = 5a = a + 7First, we create a variable called a and assign avalue of 5 to it. Second, we recall the value of a,add 7 to it, and assign the expression result to a
16. 16. 16 of 77Module 4 : Variables, Data types, and OperatorsAssignment Operator• Basic syntax:Left Hand Side (LHS) = Right Hand Side (RHS)• RHS is an expression and LHS is a variable• What “assignment” means is:1) Evaluate the expression on RHS2) Take the resulting value and associate(assign) it with the name (variable) on the LHS(in the namespace)
17. 17. 17 of 77Module 4 : Variables, Data types, and OperatorsExamples• Example: x = 2 + 3 * 5evaluate expression (2+3*5): 17update the value of x to reference 17• Example (y has value 2): y = y + 3evaluate expression (y+3): 5update the value of y to reference 5NOTE: If the variable name appears for thefirst time, create the variable in namespace!
18. 18. 18 of 77Module 4 : Variables, Data types, and OperatorsExamples• Examples:myInt = 5 OkmyInt + 5 = 7 Invalid SyntaxmyInt = print("hello") Invalid Syntaxprint myInt = 5 Invalid SyntaxWhy?
19. 19. 19 of 77Module 4 : Variables, Data types, and OperatorsMore ExamplesBoth aInt and bFloat got the same reference!!!
20. 20. 20 of 77Module 4 : Variables, Data types, and OperatorsExercise: What printed out?
21. 21. 21 of 77Module 4 : Variables, Data types, and OperatorsResult… Reference is Tricky!!!Result:A newreference
22. 22. 22 of 77Module 4 : Variables, Data types, and OperatorsChained assignment• Let’s say we want more variables totake the same value:a = b = 1a = b = c = 101. Don’t make it too long or clumsy…Readability!!!2. How about this? a = b = 5 = c = 10
23. 23. 23 of 77Module 4 : Variables, Data types, and OperatorsSwapping two values• Let’s say we want to swap valuesa = 1b = 2• Can we do this?a = bb = aThen??? Correct???Computationally incorrect!!! Why?
24. 24. 24 of 77Module 4 : Variables, Data types, and OperatorsSwapping two values• One standard way in many programminglanguages is to use a temporary variableas a buffer:tmp = aa = bb = tmpWe can then swap the reference (computationally)!
25. 25. 25 of 77Module 4 : Variables, Data types, and OperatorsMultiple Assignment• But Python has a special featurea = 1b = 2a,b = b,a• Use comma for multiple assignment• Swapping can be done in one line!!!• Note: it supports more than two elementsa,b,c = 10,11,12• Make sure same number ofelements on LHS and RHS• Python makes the tmp buffer for u(implicitly, hidden from your sight)
26. 26. 26 of 77Module 4 : Variables, Data types, and OperatorsCASE STUDY: Fibonacci sequence• Problem: Generate the Fibonacci sequence1,1,2,3,5,8,13,21,…• Mechanism1 + 1 -> 2 1,1,21 + 2 -> 3 1,1,2,32 + 3 -> 5 1,1,2,3,53 + 5 -> 8 1,1,2,3,5,8……
27. 27. 27 of 77Module 4 : Variables, Data types, and Operators• Python implementation:• Use a and b to keep track of two consecutivevalues in the sequence for each iteration• and update them iteratively usingmultiple assignmentPython is simple andgood for rapid prototypingCASE STUDY: Fibonacci sequence
28. 28. 28 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
29. 29. 29 of 77Module 4 : Variables, Data types, and OperatorsData types• In Python, every “thing” is an object withtype and name(s) (in case referenced bymore than one variables), e.g.,• integers: 5• floats: 1.2• booleans: True• strings: “anything” or ‘something’• lists: [,]: [‘a’,1,1.3]• others we will seeIn Python, bothsingle & doublequotes are for string
30. 30. 30 of 77Module 4 : Variables, Data types, and OperatorsWhat is a Data Type?• A type in Python essentially defines:• the internal structure (the kind of data itcontains)• the kinds of operations you can perform• abc.capitalize() is a method youcan call on strings, but not integers• Some types have multiple elements(collections), we’ll see those later
31. 31. 31 of 77Module 4 : Variables, Data types, and OperatorsBasic Types in Python• Numbers:• Integers1, -27• Floating point numbers (Real)3.14, 10., .001, 3.14e-10, 0e0• Complex Numbers: 2 + 3j• Booleans: True, False• String and other types
32. 32. 32 of 77Module 4 : Variables, Data types, and OperatorsNumbers: Integers• Designated “int”• Note: Python 3• Unlimited precision!!!!!!!1 + 1000 + 10000000000000000000000000• Note: Python 2 (if you know…)• There are two categories of integers: “long”and “int”, but they are combined into onetype, basically “long,” in Python 3
33. 33. 33 of 77Module 4 : Variables, Data types, and OperatorsNumbers: Floating Point• Designated “float”• Floating point numbers are real numberswith decimal points:3.14, 10., .001, 3.14e-10, 0e0• Values stored in floating point are usuallyapproximated, e.g.,Integers haveexact precision!!!But not float…
34. 34. 34 of 77Module 4 : Variables, Data types, and OperatorsNumbers: Complex Numbers• Designated “complex”• Python provides also complex numbers:real part + imaginary part J(J can be upper or lower case)• Real and imaginaryparts input can bein integer or floatingpoint numbers• No space before JNo space here
35. 35. 35 of 77Module 4 : Variables, Data types, and OperatorsNumbers: Complex Numbers• Use z.real and z.imag to extract thereal and imaginary partsNote: we use thedot operator here toget the parameters(similar syntax likemath.pi for modules)
36. 36. 36 of 77Module 4 : Variables, Data types, and OperatorsBoolean• Designated “bool”• For logical operations, see Module 6• Either True or False (capitalize T and F!)Python is casesensitive!!!
37. 37. 37 of 77Module 4 : Variables, Data types, and OperatorsString• Designated “str”• First collection type you learnt• Collection type contains multiple objectsorganized as a single object type• String is basically a sequence, typically asequence of characters delimited bysingle (‘…’) or double quotes (“…”)
38. 38. 38 of 77Module 4 : Variables, Data types, and OperatorsDuck-typing• Compared to C and Java, you may wonder“How Python know the data types?”• Python uses Duck-typing:“When I see a bird that walks like a duckand swims like a duck and quacks like aduck, I call that bird a duck.”Four variables!Their types?
39. 39. 39 of 77Module 4 : Variables, Data types, and OperatorsKeep Track of Data Types!!!• Python does not have variabledeclaration like Java or C to announceor create a variable• We create a variable by just assigninga value to it and the type of the valuedefines the type of the variable• If we re-assign another value to thevariable, its type can change!!!• So… KEEP TRACK!!!
40. 40. 40 of 77Module 4 : Variables, Data types, and OperatorsKeep Track of Data Types!!!• A variable in Python can have differenttype at different time
41. 41. 41 of 77Module 4 : Variables, Data types, and OperatorsThe type function• In Python, the type function allows you toknow the type of a variable or literal:
42. 42. 42 of 77Module 4 : Variables, Data types, and OperatorsTextbook: Hungarian notation• Variable naming: append the name of thetype to the variable name:Note the name!
43. 43. 43 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
44. 44. 44 of 77Module 4 : Variables, Data types, and OperatorsData Conversion• Converting a value to other type byreturning a new value of that type• Must be compatible and reasonablee.g., cannot convert "abc" to integer• There are conversion operationsassociated with the type itself:int(someVar) converts and returns an integerfloat(someVar) converts and returns a floatstr(someVar) converts and returns a string
45. 45. 45 of 77Module 4 : Variables, Data types, and OperatorsWhat are the types?Let’s keep track of them!
46. 46. 46 of 77Module 4 : Variables, Data types, and OperatorsWhat happens if weconvert a float to aninteger?Truncated!!!!!!!!(remove anything afterthe decimal point)Want to round off?… int(a+0.5)
47. 47. 47 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
48. 48. 48 of 77Module 4 : Variables, Data types, and OperatorsWhat are Operators?• For each type, there is a set of operatorsallowing us to perform computation on that type• Some symbols are used for different purposesfor different types; we call this operatoroverloaded (this is called overloading)• E.g., “+” is addition for integers butconcatenation for strings (see module 8)
49. 49. 49 of 77Module 4 : Variables, Data types, and OperatorsTypes of OperatorsBasic types of operators:1. Assignment operator = (covered already)2. Arithmetic operators3. Relational operators (comparison)4. Logical operators5. is operatorNote: bitwise operators – see next module
50. 50. 50 of 77Module 4 : Variables, Data types, and Operators#2: Arithmetic Operators• Integer operators• addition and subtraction: +, -• multiplication: *• division• quotient: /• remainder: %• exponent (exp): **• Floating point operators• add, subtract, multiply, divide, exp: +, -, *, /, **quotientremainder
51. 51. 51 of 77Module 4 : Variables, Data types, and Operators#2: Arithmetic Operators* Note: do not mix up / and (backslash)
52. 52. 52 of 77Module 4 : Variables, Data types, and OperatorsIssue #1: Binary Operators• Binary operators generally take twovalues (operands) of the same type *and return values of the same typeBut… for division:Integer divisionproduces float!!!A new feature inPython 3 but not inPython 2, C/C++, etc.Note: Unary operator – one value, e.g., -3 or +2.0
53. 53. 53 of 77Module 4 : Variables, Data types, and OperatorsIssue #2: Division in Python• Difference between Python versions:• In Python 2.x:Integer / integer → integerInteger division8 / 3 → 2• In Python 3.x:Integer / integer → float8 / 3 → 2.6666666666666665• Note: Division by Zero• 1 / 0 -> run time errorA Trick in Python 3:
54. 54. 54 of 77Module 4 : Variables, Data types, and OperatorsIssue #3: Mixed Operations• We have seen 8/3 and 8.0/3.0• How if 8 / 3.0? Different types: int and float• This is called mixed operation• In Python• Python will automatically convert thedata to the most detailed result. Thus,8 → 8.0, and the result is 2.6666666• Detail: int < float• So… actually no mixed operations.Rather, data are implicitly converted.
55. 55. 55 of 77Module 4 : Variables, Data types, and OperatorsIssue #4: Order of Calculation• General mathematical rules apply:Operators Description() Parenthesis (grouping)** Exponentiation+x, -x Positive, Negative*, /, % Multiplication, division, remainder+, - Addition, Subtraction• Note: always use parenthesis if in doubt… safe!!!3 * (4 + 5) ** 2Increaseinpriorty
56. 56. 56 of 77Module 4 : Variables, Data types, and OperatorsIssue #5: Augmented Assignments• These operations are shortcut• Make the code easier to readShortcut EquivalencemyInt += 2 ↔ myInt = myInt + 2myInt -= 2 ↔ myInt = myInt - 2myInt /= 2 ↔ myInt = myInt / 2myInt *= 2 ↔ myInt = myInt * 2myInt %= 2 ↔ myInt = myInt % 2
57. 57. 57 of 77Module 4 : Variables, Data types, and Operators• Compare two numbers (float or int) andreturn a boolean: either True or Falsegreater than or equal tof >= 6.0>=greater thanf > 5.0>less than or equal tod <= 4<=less thanc < 3<not equal tob != 2!=equal toa == 1==meaningexampleoperator#3: Relational Operators
58. 58. 58 of 77Module 4 : Variables, Data types, and OperatorsReturn Trueif either oneis True(num1 > num2) or (num2 >num3)orReturn Trueonly if bothare True(num1 > num2) and (num2 >num3)andFlip T/Fnot num < 0notmeaningexampleoperator#4: Logical Operators• Logical operators connect boolean valuesand expressions and return a boolean valueas a result: not, and, or
59. 59. 59 of 77Module 4 : Variables, Data types, and OperatorsExamples• Examples:have_holidays == True and saving >= 10000temperature > 37.5 and hasMedicine == FalseMathScore < 50 or EngScore < 50 or …MathScore < 50 and EngScore < 50 and …Num % 2 == 0 and Num % 3 == 0-> Num % 6 == 0What do they meaning?
60. 60. 60 of 77Module 4 : Variables, Data types, and OperatorsShort circuitGiven p=True, q=True, r=False, s=False• Short-circuit for andIf we evaluate:( p and q and r and s )• Short-circuit for orIf we evaluate:( s or r or q or p )We know the expressionis False when we reach rWe know the expressionis True when we reach qThink about the logical meaning!!http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not
61. 61. 61 of 77Module 4 : Variables, Data types, and Operators• In Python (not in most languages), chainedcomparisons work just like you would expectin a mathematical expression:• Say, myInt has a value 50 <= myInt and myInt <= 5True0 <= myInt <= 5True0 <= myInt <= 5 > 10FalseChained ComparisonsJust apply eachoperator to compare itstwo neighboring valuesEven for thissame meaning(implicit “and”)
62. 62. 62 of 77Module 4 : Variables, Data types, and OperatorsExerciseWant to check your answers? Just try it in Python
63. 63. 63 of 77Module 4 : Variables, Data types, and OperatorsCast study:Google Search uses Booleans• All terms are and’ed together by default• You can specify or (using OR)• You can specify not (using -)Example is:‘Punch’ and (‘Bill’ or ‘William’) and not ‘gates’
64. 64. 64 of 77Module 4 : Variables, Data types, and Operators#5: is operator• Recall the namespace concept:float1 = 2.5float2 = 2.5float3 = float2• When we run “float3 = float2,”both float3 and float2 get the same reference
65. 65. 65 of 77Module 4 : Variables, Data types, and Operators#5: is operator• It checks if two variables have the samereference while == compares values onlyFunction id returns theidentity number of a variable
66. 66. 66 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
67. 67. 67 of 77Module 4 : Variables, Data types, and OperatorsPowerful Data types• Some very powerful data types in Python• List – sequence of values• Dictionary – values with keys• Set – a collection of unique elements• Point – XYZ• Line Segment – two points(See textbook and Python website for detail;note: they are very useful; not examinableunless covered in 2nd part of this course)
68. 68. 68 of 77Module 4 : Variables, Data types, and OperatorsA glimpse: List• Python allows us to create a list of elements• Like string, a list is also a sequence but uses [ ]
69. 69. 69 of 77Module 4 : Variables, Data types, and OperatorsModule random• Provides some powerful functions:• randint( a , b ):Return a random integer in [a,b] (inclusive)• choice( x ):Return a random element in sequence x;x has to be non-empty• shuffle( x ):Shuffle the sequence x in place; x can be astring and can be a setYou need to import random!!!
70. 70. 70 of 77Module 4 : Variables, Data types, and OperatorsDifferentelements pickedat different time(same statement)s1 is changed!
71. 71. 71 of 77Module 4 : Variables, Data types, and OperatorsBut hold on…• Is random really random?• Computation are deterministic. Computerscannot generate true random numbers.• So what?Pseudo random!!!* Pseudo random number generatorcreated by mathematical functions !!(Example? See the end of next lecture module)
72. 72. 72 of 77Module 4 : Variables, Data types, and OperatorsTopics• Variables• Assignment Operator• Data Types• Data Conversion• Operators• Powerful Data Types and Random Module• Case Study: Calculator Example
73. 73. 73 of 77Module 4 : Variables, Data types, and OperatorsCalculator Example• Before the example, let’s learn an interestingand powerful Python function: exec• It takes a string as an input and execute it like aPython statement in the command shellExecute this string
74. 74. 74 of 77Module 4 : Variables, Data types, and OperatorsCalculator Example• Why powerful? Check this:Repeat the indented blockUser inputExecute itNote: + is the concatentationoperator to connect strings
75. 75. 75 of 77Module 4 : Variables, Data types, and Operators• We can read user inputs from command shelland dynamically execute them like “code”!!!• Not many programming languages can do thisNote: Python - interpreter!!!Calculator Example
76. 76. 76 of 77Module 4 : Variables, Data types, and OperatorsTake Home Messages• Variables:– Namespace and name reference concept• Assignment Operator: Single, Chained, Multiple• Data Types:– Numbers (integers and float), Booleans, String(collection types)– Duck-typing, type function, data conversion• Operators– Division, mixed operators, order of operations andparentheses, augmented assignments, relational andlogical operators• Additional: list, random module, and exec
77. 77. 77 of 77Module 4 : Variables, Data types, and OperatorsReading Assignment• TextbookChapter 1: Beginnings1.4 to 1.7(and also Chapter 0.8 about representing data)