4-IntroPython
4-IntroPython
You had me at
turn_left()
"""
To run a race that is 9 avenues long, we need to move
forward or jump hurdles 8 times.
"""
def main():
for i in range(8): Decomposition principle:
if front_is_clear(): Consistent Each function should solve
move()
else: indentation one step of problem
jump_hurdle()
"""
Pre-condition: Facing East at bottom of hurdle
Post-condition: Facing East at bottom in next avenue after hurdle
"""
def jump_hurdle(): Descriptive names
ascend_hurdle()
move() Short functions (snake_case)
descend_hurdle() (usually 1-15 lines)
Piech and Sahami, CS106A, Stanford University
What’s Mozart Doing Now?
if mehran_teaching():
not_funny()
while mehran_teaching():
not_funny()
1. Introduction to Python
2. Understanding variables
def main():
print("hello, world!")
This is on a PC.
On Macs: python3 helloworld.py
Our First Python Program
You’re now all Python
programmers!
hey_that_looks_
like_what_I_
taught_them()
x 10
x 10
5
x 12
5
x 12
num_students 700
num_in_class 550
num_absent 150
Piech and Sahami, CS106A, Stanford University
Types
• Each suitcase knows what type of information it carries
num_students = 700
num_students 700
int
– Value stored in suitcase is an integer (called an int in Python)
– Suitcase keeps track of type of data that is stored there
num_students = 700.0 # note decimal point
– Now, value stored is a real number (called a float in Python)
float
num_students 700.0
string
num1 "9"
num1 9
int
Piech and Sahami, CS106A, Stanford University
Recall, Our Program
def main():
print("This program adds two numbers.")
num1 = input("Enter first number: ")
num1 = int(num1)
num2 = input("Enter second number: ")
num2 = int(num2)
total = num1 + num2
print("The total is " + str(total) + ".")
num1 9
10
3.5
x = 10
Piech and Sahami, CS106A, Stanford University
Multiple values in print
• You can also print multiple items separating them
with commas
– By default, a space is printed between each item
def main():
x = 4
y = 0.2
print(x, y)
print("x =", x, "and y =", y)
4 0.2
x = 4 and y = 0.2
1. Introduction to Python
2. Understanding variables