01D Programming Part 2 (Homework)
01D Programming Part 2 (Homework)
2022/23 Term 1
SMU Classification: Restricted
Road Map
In-class Ex 4: T31-40
• The next Tutorial Project requires you to write two functions:
celsius()
countertop()
function definition
def f2(x, y):
return x * y
when calling it:
f2(x=10, y=20)
SMU Classification: Restricted
Boolean Expressions
• A Boolean expression is a combination of values, variable names and operators,
and
– Always evaluates to either True or False.
• E.g. of Boolean expressions:
– 10 > 5
– 10 < 10
– 10 <= 10
– x == 10
• These are Boolean operators:
<, <=, >, >=, ==, !=
• Important:
== is not the same as =
SMU Classification: Restricted
Conditional Execution
• New keywords: if, else
• tax_rate is a function to compute tax rate depending on income
level:
– People who earn less than $10k will be taxed at 0%, but
– People who earn $10k or more will be taxed at 5%
SMU Classification: Restricted
…Conditional Execution
• New keyword: elif (else if)
• Let's say the tax rate calculation rules have changed to 3 tiers:
– People who earn less than $10k will be taxed at 0% (same), but
– People who earn $10k to below 20k will be taxed at 5%, and
– People who earn $20k or more will be taxed at 7%.
SMU Classification: Restricted
In-class Ex 5: T41-46
• Try Tutorial Project T41-46 (p.52 of the PDF or p.38 of
textbook)
– Go to
https://colab.research.google.com/drive/19wneP3Hm4VovweLAZWF
9VqEpwpxXoB_H
SMU Classification: Restricted
• When calling a function, once the program reaches a "return" statement, the
function terminates immediately.
SMU Classification: Restricted
To be viewed as 1 statement.
Strings
• We have seen integers, floats and booleans. Data can be stored as strings as
well.
• A string is a set of characters (letters, digits, punctuation marks, spaces etc.) enclosed in quotes.
• We can store strings in variables:
>>> s = "hello"
• We can do interesting things with strings:
>>> "pine" + "apple" String concatenation
>>> s + "world"
>>> s * 3 Returns a Boolean depending on whether
>>> "hell" in s "hell" is a substring of s
>>> str.count(s,"l")
>>> s.count("l")
SMU Classification: Restricted
In-class Ex 6: T47-65
• Try Tutorial Project T47-65 (p.55 of the PDF or p.41 of textbook)
– Go to
https://colab.research.google.com/drive/1NvGDjZn4xAdCacqL6epTYoGwBGJPnrM9
In-class Ex 7: T66-71
• Try Tutorial Project T66-71 (p.60 of the PDF or p.46 of textbook)
– Go to https://colab.research.google.com/drive/18PdggEz01YXoV0LZoH1mIVUjjtsuVi0n
– You will get to use the type() function.
Summary
• Programming part 1 (week 1 class time):
– Arithmetic operations (operand, operator)
– Integers vs. floats
– Calling a function (e.g., sqrt)
– Using variables
• Programming part 2 (this slide deck)
– Writing a function for others to call
– Conditionals (if, elif, else)
– Strings
– type() function
• In week 2, we will look at other Python features such as loops and lists.