Introduction to Python - Lecture 4
Zohair ul Hasan
Last week's tasks
print(), input(), and len() A function is like a mini-program within a program
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
hello()
hello()
hello()Output:
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
print('Howdy!')
print('Howdy!!!')
print('Hello there.')print("Hello World")
len("hi!")
print("Hello World")
len("hi!")
Arguments
def hello(name):
print('Hello, ' + name)
hello('Alice')
hello('Bob')Output:
Hello, Alice
Hello, Bobdef hello(name):
print('Hello, ' + name)
hello('Alice')
hello('Bob')Output:
Hello, Alice
Hello, BobArguments
def hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')Output:
Hello, Alice
Hello, BobParameter
Arguments
Parameters are variables that store arguments.
Variables defined in the function parameters are "forgotten" when the function returns.
def hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')
print(your_name)Output:
Hello, Alice
Hello, Bob
Traceback (most recent call last):
File "/Users/zohair/Projects/test/testing-debugger/test.py", line 6, in <module>
print(name)
^^^^
NameError: name 'your_name' is not defineddef hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')Define statement (or function definition). Defines the hello function.
def hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')Define statement (or function definition). Defines the hello function.
Calls the created function
def hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')Define statement (or function definition). Defines the hello function.
Calls the created function
Value being passed to function is called an argument
def hello(your_name):
print('Hello, ' + your_name)
hello('Alice')
hello('Bob')Define statement (or function definition). Defines the hello function.
Calls the created function
Value being passed to function is called an argument
Variables that have an argument assigned to them are called parameters
def hello(name, day):
print('Hello, ' + name + '. Today is ' + day + ".")
hello('Alice', 'Thursday')
hello('Bob', 'Friday')Output:
Hello, Alice. Today is Thursday.
Hello, Bob. Today is Friday.>>> len('hello!')
6
Value that a function call evaluates to is called the return value of the function
We can specify the return values of a function using the return statement
A return statement consists of the following:
return keywordIf an expression is used with the return statement, the return value will be whatever the expression evaluates to
import random
def get_answer(answer_number):
if answer_number == 1:
return 'It is certain'
elif answer_number == 2:
return 'It is decidedly so'
elif answer_number == 3:
return 'Yes'
elif answer_number == 4:
return 'Reply hazy try again'
elif answer_number == 5:
return 'Ask again later'
elif answer_number == 6:
return 'Concentrate and ask again'
elif answer_number == 7:
return 'My reply is no'
elif answer_number == 8:
return 'Outlook not so good'
elif answer_number == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = get_answer(r)
print(fortune)r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)print(getAnswer(random.randint(1, 9)))Remember, expressions are composed of values and operators. A function call can be used in an expression because the call evaluates to its return value.
There is a value called None, which represents the absence of a value
This value is the only value that exists for the NoneType datatype
>>> type(None)
<class 'NoneType'>Just like the Boolean True and False values, None must be typed with a capital N
None is helpful when you need to store something that won't be confused for a real value in a variable
For example, None is the return value for print()
The print() function simply displays text on the screen, but does not need to return anything like len() or input() do
Since all function calls are required to resolve to a value, it returns None
>>> spam = print("Hello!")
Hello!
>>> print(spam)
NoneBy default, if a function doesn't have a return statement, Python adds a return None statement at the end of the function behind the scenes.
Writing a return statement without a value or expression after it also returns None
Usually arguments are identified by their position in the function call
random.randint(1, 20)
Usually arguments are identified by their position in the function call
random.randint(1, 20)
Lower end of range
Higher end of range
Keyword arguments are identified by the keyword put before them when calling the function instead of through their position
print("Hello", end='')
E.g.
Keyword arguments are often used for optional parameters.
For example, the print() function has the optional parameters end and sep to specify what should be printed at the end of its arguments and between its arguments (separating them) respectively
print('Hello')
print('World')Output:
Hello
WorldThe print() function automatically adds a newline character to the end of the string it is passed
However, you can set the end keyword argument to change the newline character to a different string
print('Hello', end='')
print('World')Output:
HelloWorldPassing multiple arguments to the print() function will automatically separate them with a single space
>>> print('cats', 'dogs', 'mice')
cats dogs miceYou can replace the default separating string by passing the sep keyword argument a different string
>>> print('cats', 'dogs', 'mice', sep=',')
cats,dogs,miceWe can add keyword arguments to the functions we create as well, but we need to learn about lists and dictionaries before we can do so
Python will remember which line of code called the function so that the execution can return there when it encounters a return statement
If that original function called other functions, the execution would return to those function calls first, before returning from the original function call.
def a():
print('a() starts')
b()
d()
print('a() returns')
def b():
print('b() starts')
c()
print('b() returns')
def c():
print('c() starts')
print('c() returns')
def d():
print('d() starts')
print('d() returns')
a()Output:
a() starts
b() starts
c() starts
c() returns
b() returns
d() starts
d() returns
a() returnsThe call stack is how Python remembers where to return the execution after each function call. The call stack isn’t stored in a variable in your program; rather, Python handles it behind the scenes. When your program calls a function, Python creates a frame object on the top of the call stack. Frame objects store the line number of the original function call so that Python can remember where to return. If another function call is made, Python puts another frame object on the call stack above the other one.
When a function call returns, Python removes a frame object from the top of the stack and moves the execution to the line number stored in it. Note that frame objects are always added and removed from the top of the stack and not from any other place.
The top of the call stack is which function the execution is currently in. When the call stack is empty, the execution is on a line outside of all functions.
Follow the activity at https://itp.zohair.dev/activities/local-and-global-scope to learn more about local and global scope
Follow the activity at https://itp.zohair.dev/activities/exception-handling to learn more about exception handling
Follow the activity at https://itp.zohair.dev/activities/zigzag to practice the concepts we learned today.
Please complete the homework at: https://itp.zohair.dev/homeworks/collatz-sequence