Lecture 05
2022-10-10 | Week 3 | by Ashwin Ranade
Table of Contents
Hey everyone, Ashwin here. This continues from last lecture, and covers the slides from python_intro_v1 from 1 to 19. The first part of this lecture (Algebraic Data Types and Immutability) is covered in Lecture 4.
Note: In a code block, the characters below -------------
represents the output of the Python program above the -------------
. This holds for all the lecture notes that I made.
For example:
<python program>
----
<output of python program>
Background
Python uses:
- quick and dirty scripting
- industrial scripts
Basic Python facts:
- open source
- no compiler, just interpreters (we will use CPython)
- Avoid Python for: writing efficient programs (since it’s interpreted)
- note: Python modules can use code from other languages (e.g. C++) for optimization (e.g. PyTorch, TensorFlow, NumPy)
Python Shell
Python Shell can be used:
- interactively
- to run programs saved in
.py
filesclimberkip$ python3 Python 3.9.6 <a bunch more boilerplate removed for clarity> >>> def f(x,y): ... print(f'{x} + {y} is {x+y}') ... >>> f(10,20) 10 + 20 is 30 >>> bar = 10 >>> bar/3 + 5 8.3333333333333334 >>> ^D
...
indicates multi-line function- exit shell with Ctrl-D or
quit()
Basic Intro, through Challenges
import this
=> Python Design Principles link
- Formatting: blocks defined by colon + indentation; no block delimiter
{
or statement delimiter;
- Program Execution: Interpreter runs file from top-to-bottom; no default main() function
Pythonic main function:
if __name__ == "__main__":
main()
-
Python sets
__name__
to__main__
, telling us to run main function -
Functions:
- no parameter type annotation or return types
- default params allowed; we can explicitly specify param names when calling functions
ex:
def smoosh(x,y):
return x + y
print(smoosh(y=10,x=20))
This returns 30
Variables and Types
- definition not required; type not required; variables can be assigned to different types over time
- same function can be applied to different types
ex: overloaded +
operator for strings and ints
def add_n_print(x,y):
print(x+y)
add_n_print(10,20)
add_n_print("I <3 ", " coding")
Type Errors + Dynamic Type Checking
def add_n_print(x, y):
print(x + y) # Line 1
def main():
add_n_print('foo', 5) # Line 2
Error:
TypeError: can only concatenate str (not "int") to str
Error is generated when the code reaches line #1 at runtime, after add_n_print
is called from the main function.
Python uses dynamic checking, versus statically typed languages like C++. Dynamic checking means we only check the operand types the moment the operation occurs.
Python type hints are NEVER enforced by Python interpreter, although they are used by 3rd party tools and are considered good practice.
The following code runs fine:
def make_bday_msg(name: str, age: int) -> str:
msg: str = f'Happy {age}th birthday, {name}!'
return msg
say_this: str = make_bday_msg(3.14159, 'hamsters')
print(say_this)
And prints:
Happy hamstersth birthday, 3.14159!
More Python Syntax
Python has big ints that can hold any size integer; the array representing the integer can dynamically grow to any size.
THRESHOLD = 1000000000
big = 2**200 # exponentiation
if big > THRESHOLD:
print(f'{big} is really big!')
---
1606938044258990275541962092341162602522202993782792835301376 is really big!
-
all caps variables can be considered constants, although they can be reassigned, so technically not constants
/
operator always produces a double result://
always produces an integer result (integer division)kittens = 5 / 2 #2.5 puppies = 5 // 2 #2
- Python’s
input()
function always returns a string- we can convert to different types with
float()
orint()
#assume input is Binh 3.62 18 [each on a different line] nm = input('Your name: ') print(f'{nm} is {type(nm)}') gpa = float(input('Your GPA: ')) print(f'{gpa} is {type(gpa)}') age = int(input('Your age: ')) print(f'{age} is {type(age)}') --- Your name: Binh Binh is <class 'str'> Your GPA: 3.62 3.62 is <class 'float'> Your age: 18 10 is <class 'int'>
- we can convert to different types with