Coming Up
- Booleans, Relational and Logic Operators, and Conditionals (
if
statements) - Sequences, Indexing and Slicing
- Functions
1 Booleans, Relational and Logic Operators, and Conditionals
Discussion 1: Booleans
D1: What is “Boolean”? What values does it store? Can other types be converted to it?
# ints -> bool
# print(bool(0)) # 0 converts to False
# print(bool(1)) # all other values convert to True
# floats -> bool
# print(bool(0.0)) # 0.0 converts to False
# print(bool(3.1415)) # all other values convert to True
# str -> bool
# print(bool("")) # empty string converts to False
# print(bool(" ")) # all other values convert to True
# print(bool("Hi!")) # all other values convert to True
Discussion 2: Relational and Logical Operators
D2: For each of the following, identify whether it is: (a) a Boolean value; (b) a relational operator; or (c) a logical operator.
==
:!=
:or
:True
:>
:and
:>=
:<
:False
:<=
:not
:
📝 Operators
- the following is ordered from Highest to Lowest precedence
- Arithmetic Operators
()
brackets**
exponent%
modulus/remainder//
floor/integer division/
division*
multiplication-
subtraction (also a unary operator; make number negative)+
addition (also a unary operator; make number positive)
- Relational Operators
- compare two values to produce a truth (boolean) result
==
equal to!=
not equal to<
less than>
greater than<=
less than or equal to>=
more than or equal toin
- Logical Operators
- combine Boolean values to return a single truth value
not
and
or
Discussion 3: Conditionals
D3: How do we use an if statement? What are the variants? How do we know what is contained inside it and what is after?
📝 if...elif...else Structure
if <condition_1>:
<statements/operations to be executed if condition1 is True>
elif <condition_2>:
<statements/operations to be executed if condition2 is True>
...
elif <condition_x>:
<statements/operations to be executed if conditionx is True>
else:
<statements/operations to be executed if all conditions are False>
Exercise 1
E1: Evaluate the following truth expressions:
True or False
:True and False
:False and not False or True
:False and (not False or True)
:
📝 Logical Operator Truth Tables
a | b | a and b | a or b |
---|---|---|---|
False | False | False | False |
False | True | False | True |
True | False | False | True |
True | True | True | True |
a | not a |
---|---|
False | True |
True | False |
Exercise 2
E2: For each of the following if statements, give an example of a value for var which will trigger it and one which will not.
[object Object]
[object Object]
[object Object]
[object Object]
Exercise 3
E3: What’s wrong with this code? How can you fix it?
letter = input("Enter a letter: ")
if letter == 'a' or 'e' or 'i' or 'o' or 'u':
print("vowel")
else:
print("consonant")
Exercise 4 (assignment VS equality)
E4: What’s wrong with this code? How can you fix it?
eggs == 3
if eggs = 5:
print("spam")
else:
print("not spam")
2 Sequences, Indexing and Slicing
Discussion 4: Sequences
D4: What is a “Sequence”? What sequences have we seen so far? What operators can we use with sequences?
📝 Sequence Operations
# Create copies of sequences with *
# print("hello"*2)
# print(("python", 2, [1, 2])*4) # tuples and lists are sequences too (later)
# Concatenate sequences with +
# print("good " + "afternoon")
# Use for...in... to loop through sequences (later)
# for letter in "awesome":
# print(letter)
Discussion 5: Indexing
D5: What is indexing? How can you do it?
Dicussion 6: Slicing
D6: What is slicing? How can you do it?
Exercise 5
p | y | t | h | o | n | |
---|---|---|---|---|---|---|
index | 0 | 1 | 2 | 3 | 4 | 5 |
negative index | -6 | -5 | -4 | -3 | -2 | -1 |
- length: 6
- Slicing:
[start:end:step]
E5: Evaluate the following given the assignment s = "python"
s[1]
:s[-1]
:s[1:3] + s[3:5]
:s[10]
:s[10:]
:s[-4:-2]
:s[:-4]
:s[::2]
:s[::-1]
:
# only use the code block for checking your answers!
3 Functions
Discussion 7: Functions
D7: What is a “function”? How do we call (use) one? How do we define one ourselves?
📝 Function (and Docstring) Structure
CONSTANT = 0 # declare constants before all functions
def <function-name>(<parameters>):
"""
docstring describing what the function does.
"""
<function-body>
def sum(x, y):
"""Returns the sum of two integers."""
return x + y
sum(1, 2) # function call
# print(sum(1, 2)) # printing the returned value
# Viewing Docstrings
# print(sum.__doc__)
# print(print.__doc__) # built-in functions also have docstrings
Ways to structure docstrings
short and sweet one-liners
- example:
def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b
- example:
detailed params/args, returns, raises, example
examples:
def add_binary(a, b): """ Returns the sum of two decimal numbers in binary digits. Parameters ---------- a (int): A decimal integer b (int): Another decimal integer Returns ------- binary_sum (str): Binary string of the sum of a and b """ #...
What are the most common Python docstring formats? [closed] | stackoverflow
Discussion 8: Return
D8: What does it mean to “return” a value from a function and why would we want to? Does a function always need a return value?
def example_1():
return 1
print("abc")
return 2
return 3
print(example_1) # what do you think this will return?
Discussion 9: Function of Functions
D9: Why should we use functions? Could we live without functions?
Discussion 10: Brackets and Functions
D10: Why are brackets important when calling a function? Are they needed even if it takes no arguments?
Exercise 6
E6: What’s wrong with this code? How can you fix it?
def calc(n1, n2):
answer = n1 + (n1 * n2)
print(answer)
num = int(input("Enter the second number: "))
result = calc(2, num)
print("The result is:", result)
Coding Problems
Problem 1
"""
P1: Write a function which takes a string as a single argument, and returns a
shortened version of the string consisting of its first three letters and then
every second letter in the rest of the word. shorten('uncalled') should return
'uncle'.
"""
Problem 2
"""
P2: Write a function which takes a sentence as a single argument (in the form of
a string), and evaluates whether it is valid based on whether the first letter is
capitalised and the last character is a full stop. It should return a Boolean
value True or False.
"""
Problem 3
"""
P3: Write a program which asks the user for two numbers and an operator out of
+, -, / and * and performs that operation on the two numbers, printing the
result.
"""