Learning To Code With Python!
Learning To Code With Python!
a value
input
How can we ask a user for information?
name
Chris
If you need to remember more than one value, just
create more variables
name favoriteMovie
Real
Chris
Genius
city
Pasadena
You can access the value you stored later in your
code
That’s intellisense.
Have a user enter their postal code and then display that postal
code in all upper case letters even if the user typed it in lowercase?
Ask someone for their name and then display the name
someone with the first letter of their first and last name
uppercase and the rest of their name lowercase?
age = 42
print(age)
With numbers you can do math
width = 20
height = 5
perimeter = 2*(width+height)
print(perimeter)
Math rules haven’t changed since Grade 4
Order of operations
( ) parentheses
** exponent (e.g. **2 squared **3 cubed)
*/ multiplication and division
+ - addition and subtraction
Of course this means we have more ways to make
mistakes too!
salary = '5000'
bonus = '500'
payCheck = salary + bonus
print(payCheck)
Because we put quotes around the values, the
program thought salary and bonus were strings
so it concatenated instead of adding
salary = 5000
bonus = 500
payCheck = salary + bonus
print(payCheck)
Could you ask the user to enter their bonus and
salary values?
datetime
What is today’s date?
• The datetime class allows us to get the current date and time
import datetime
import datetime
currentDate = datetime.date.today()
#strftime allows you to specify the date format
print (currentDate.strftime('%d %b,%Y'))
What the heck are %d %b and %Y?
“Please attend our event Sunday, July 20th in the year 1997”
import datetime
currentDate = datetime.date.today()
#strftime allows you to specify the date format
print (currentDate.strftime
('Please attend our event %A, %B %d in the year %Y'))
So… what if I don’t want English?
Can you think of any situations where this code might not
work the way we want?
Can I ask a user for their birthday?
birthday = input ("What is your birthday? ")
print ("Your birthday is " + birthday)
string
birthdate = datetime.datetime.strptime(birthday,"%m/%d/%Y")
If statements
Sometimes you want your code to react differently to
different situations
• If the user chooses express shipping, charge an extra $10
• If I win the lottery quit my job
• If the hockey player gets the puck in the net, add one to the
score
If statements allow you to specify code that only
executes if a specific condition is true
if answer == "yes" :
if not answer == "no" :
deposit = 150
if deposit > 100 :
print("You get a free toaster!")
print("Have a nice day")
if country == "CANADA" :
print("Hello")
elif country == "GERMANY" :
print("Guten Tag")
elif country == "FRANCE" :
print("Bonjour")
if country == "CANADA" :
print("Hello")
elif country == "GERMANY" :
print("Guten Tag")
elif country == "FRANCE" :
print("Bonjour")
else :
print("Aloha/Ciao/G’Day")
If you win the lottery and the prize is over a million
dollars then retire to a life of luxury
• Sometimes the decision on whether to take the next step
depends on a combination of factors
• If I win the lottery, but only win $5 I can’t retire
• If the lottery gives out a million dollars but I didn’t win, I can’t
retire
• I can only retire if I win the lottery and the prize was over a
million dollars
Using “and” allows you to require
multiple conditions to be true
The “and” is only evaluated as True if both conditions
are True.
Repeating code
For loops
Did you know Python works as an Etch a Sketch?
import turtle
turtle.forward(100)
turtle likes to draw
import turtle
turtle.color('green')
turtle.forward(100)
turtle.right(45)
turtle.color('blue')
turtle.forward(50)
turtle.right(45)
turtle.color('pink')
turtle.forward(100)
You can probably guess what some of the turtle
commands do
import turtle
turtle.forward(100) We are just repeating
turtle.right(90) the same two lines of
turtle.forward(100) code
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
Loops allow us to repeat the same line of code as
often as we want
Number of times to execute
import turtle the code in the loop
for steps in range(4):
turtle.forward(100)
turtle.right(90)
import turtle
for steps in range(4):
turtle.forward(100)
turtle.right(90)
turtle.color('red')
turtle.forward(200)
Now we have new ways to mess up our code!
import turtle
for steps in range(4):
turtle.forward(100)
turtle.right(90)
for moresteps in range(4):
turtle.forward(50)
turtle.right(90)
Just for fun
import turtle
for steps in range(5):
turtle.forward(100)
turtle.right(360/5)
for moresteps in range(5):
turtle.forward(50)
turtle.right(360/5)
We could use a variable to decide the number of
sides our object will have
import turtle
nbrSides = 6
for steps in range(nbrSides):
turtle.forward(100)
turtle.right(360/nbrSides)
for moresteps in range(nbrSides):
turtle.forward(50)
turtle.right(360/nbrSides)
What’s the advantage of using a variable here instead
of just typing in the number?
import turtle
nbrSides = 6
for steps in range(nbrSides):
turtle.forward(100)
turtle.right(360/nbrSides)
for moresteps in range(nbrSides):
turtle.forward(50)
turtle.right(360/nbrSides)
When we use a variable and we want to change a
value that appears in many places, we only have to
update one line of code!
import turtle
nbrSides = 6
for steps in range(nbrSides):
turtle.forward(100)
turtle.right(360/nbrSides)
for moresteps in range(nbrSides):
turtle.forward(50)
turtle.right(360/nbrSides)
Did you know you can actually look at the values
being used in the loop?
import turtle
for steps in ['red','blue','green','black'] :
turtle.color(steps)
turtle.forward(100)
turtle.right(90)
While loops
For loops allow us to execute code a fixed number of
times
import turtle
for steps in range(4):
turtle.forward(100)
turtle.right(90)
What if we don’t know how exactly how many times
to repeat the code?
• Ask for the names of everyone in a class and print each name
• Keep guessing until you get the right answer
• Read all the values in a file or in a database
While Loops allow you to execute until a particular
condition is true
You have to declare the
variable before you use
it in the loop
answer = "0" Execute the code in the loop over
and over while the variable
answer is not equal to 4
while answer != "4":
answer = input("What is 2 + 2 ")
guests = ['Christopher','Susan','Bill','Satya']
scores = [78,85,62,49,98]
You can create an empty list and add values later
guests = []
scores = []
You can reference any value in the list by specifying
it’s position in the list
guests = ['Christopher','Susan','Bill','Satya']
scores = [78,85,62,49,98]
#Print the fourth score
print(scores[3])
geek tip: We call the position in the list the index
You can count backwards to specify the entry you
want
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
print("first value is " + guests[0])
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
guests = ['Christopher','Susan','Bill','Satya']
guests.sort()
for guest in guests :
print(guest)
guests.sort()
for guest in guests :
print(guest)