02 - CM2015 - Variables, Control Flow and Functions (2022-10)
02 - CM2015 - Variables, Control Flow and Functions (2022-10)
Topic 2
Variables, Control Flow and Functions
Learning Outcomes
After completing this topic and the recommended reading, you should be able
to:
• Import modules, and use them to compute basic statistics.
• Use logic and iteration.
• Identify and use correct syntax and explain the purpose of built-in
variable types int, float and list.
Variables
• Variable is a named piece of memory whose value can change during the
running of the program; constant is a value which cannot change as the
program runs.
o Python doesn’t use constant
• Every variable in Python is an object.
• Variable can be rebind to another object of different data type.
• Most variables are immutable objects, i.e., new value is created and
rebind to variables, the old value became “garbage”.
• Example:
Variable Name
• We use variable names to represent objects (number, data structures,
functions, etc.) in our program, to make our program more readable.
o All variable names must be one word, spaces are never allowed.
o Can only contain alpha-numeric characters and underscores.
o Must start with a letter or the underscores character.
o Cannot begin with a number.
o Case-sensitive
o Standard way for most things named in Python is lower with under
§ Lower case with separate words joined by an underscore
• No use of reserved words.
Mutability
• Mutable: objects that can be modified.
o Python list and dictionary are mutable objects.
o Example:
• Immutable:
o Python tuple and others are immutable objects.
o Example:
Aliasing
• Assign a variable to another variable
• Object type: A reference/pointer is copied.
o Example:
o Example:
o https://pythontutor.com/live.html#mode=edit
Comments
• Not processed by the computer, valued by other programmers.
• Header comments
o Appear at beginning of a program or a module
o Provide general information
• Step comments or in-line comments
o Appear throughout program
o Explain the purpose of specific portion of code
• Often comments delineated by
o // comment goes here
o /* comment goes here */
o # Python uses this
Python Operations
• Assignment Operator
o “=”
o Example:
§ a = 67890/12345
# compute the ratio, store the result in ram, assign to a
# the value of a is 5.499392
§ b=a
# b pointing to value of a
• Output
o “print()”
o Example:
§ print(‘Hello World!’) # print the string literals
§ print(a) # print the value of a
• Float
o Stores real numbers
o a = 4.6
o print(type(a))
• Integer
o Stores integers
o b = 10
o print(type(b))
• Conversion
o int(a) # convert float to int => 4
o float(b) # convert int to float => 10.0
• String
o Stores strings
o phrase = ‘All models are wrong, but some are useful.’
o phrase[0:3] # slicing character 0 up to 2
=> All
o phrase.find(‘models’) # find the starting index of word
=> 4
o phrase.find(‘right’) # word not found
=> -1
o phrase.lower() # set to lower case
=> ‘all models are wrong, but
some are useful.’
o phrase.upper() # set to upper case
=> ‘ALL MODELS ARE
WRONG, BUT SOME ARE
USEFUL.’
o phrase.split(‘,’) # split strings into list, base on delimiter
=> [‘All models are wrong’,
‘ but some are useful.’]
• Boolean
o Stores logical or Boolean values of TRUE or FALSE
o k=1>3
o print(k)
o print(type(k))
• Logical operators
o Conjunction (AND): “and”
o Disjunction (OR): “or”
o Negation (NOT): “not”
a b a and b a or b not a
T T T T F
T F F T F
F T F T T
F F F F T
• Lists
o Store ordered collection of objects; mutable
o Written with square brackets “[ ]”
§ list1 = [“apple”, “banana”, “cherry”]
§ list2 = [“Handsome Koh”, 4896, 13.14, True]
o Changing elements
§ list1.append(“orange”) # add to last position
=> [‘apple’, ‘banana’, ‘cherry’,
‘orange’]
§ list1[2] = “coconut” # modify index element
=> [‘apple’, ‘banana’, ‘coconut’,
‘orange’]
§ list1.remove(“apple”) # delete elements
=> [‘banana’, ‘coconut’, ‘orange’]
§ list1.insert(2, “durian”) # insert element at position
=> [‘banana’, ‘coconut’, ‘durian’,
‘orange’]
• Sets
o Store unordered, unindexed, nonduplicates collection of objects
o Written with square brackets “{ }”
§ set1 = {“apple”, “banana”, “cherry”}
§ set2 = {“apple”, “samsung”}
o Set operations
§ set1.union(set2) # Union both sets
=> {‘apple’, ‘banana’, ‘cherry’,
‘samsung’}
§ set1.intersection(set2) # Intersect both sets
=> {‘apple’}
• Dictionaries
o Store unordered collection of objects
o Written with square brackets “{ }”, and “key:value” pair
§ thisdict = {“brand”: “Ford”, “model”: “Mustang”,
“year”: 1964}
o Accessing/modifying elements by key name
§ thisdict[“model”] => ‘Mustang’
§ thisdist[“year”] = 2018 => {‘brand’: ‘Ford’,
thisdist[“color”] = “red” ‘model’: ‘Mustang’,
‘year’: 2018,
‘color’: ‘red’}
2. Condition/Decision/Selection/Branching in Python
• Dual alternative
o Two blocks of statements, one of which is to be executed, while
the other one is to be skipped.
o Example: if…then…else
• Multiple alternative
o More than two blocks of statements, only one of which is to be
executed and the rest skipped.
o Example: if…then…else if…else; switch case
Conditional Statements
• Single alternative
o Python syntax:
o Example:
• Dual alternative
o Python syntax:
o Example:
o Example:
3. Iteration/Repetition/Loop in Python
o Example:
• Terminating early
o continue: stops the current iteration and moves to next iteration.
o break: stops the loop entirely.
eval( ) - changes the type based on the input
o Example:
• Condition-controlled Loop
o Python syntax:
o Example:
4. Functions in Python
create pipeline for the data cleaning and machine learning processes. ** more intelligent code
o Example:
Scope of Function
• Global scope
o Variables from global scope is available everywhere.
o Variables created outside of a function can be used by any
functions.
o Example:
• Local scope
o Variables from local scope is not available elsewhere.
o Variables created inside of a function cannot be used outside of the
function.
o Example:
• LEGB Rule
o Local à Enclosing à Global à Built-in scope
o Example:
o https://pythontutor.com/live.html#mode=edit
o Example:
• Make a copy
o A new copy of the reference object is made, changes will not
modify the original object.
o Example:
o https://pythontutor.com/live.html#mode=edit
Libraries
• SciPy
o Python library used for scientific computing
o Contains modules for optimization, linear algebra, integration,
interpolation, etc
• NumPy
o Python library used for working with arrays
o Performs numerical processing
• Pandas
o Python library used for data manipulation and analysis
o Work with heterogenous data, as data frame
5. Exercises
6. Practice Quiz
• Work on Practice Quiz 02 posted on Canvas.
Useful Resources
•
o http://