Python for Youth

  • refer to last week's robotic session
  • Under the hood, languages like Python program translate human language to something the machine can understand (instructions)
  • Python is an open source general purpose language, used for many things from data science, to web development to app development, etc.
  • Python emphasizes readability, compared to older langauges many default functions and commands are read like plain English.
  • ask who has done programming, who has done Python
  • Introduce repl.it, not the only way, easy for first introduction without installation of anything. FORK the repl.it and the online python interpreter that we useis here: https://repl.it/@UofTCoders/saturdayprogram
    • explain stickies -> sometimes things go wrong, not a problem! part of the learning experience.
    • we're all human!
  • Lesson outline:
    • We learn python through a game, taken from Code Club Projects
    • A brief intro to general python commands, syntax = the rules/grammar used that Python can always know what you're trying to say.
      • going more in depth with what we did in the game and explaining
        • you'll have an idea of python commands and syntax, and enough for you to go home and find tutorials for what you want to do, (almost anything!)

In [3]:
# First, let the player choose Rock, Paper or Scissors by typing the letter ‘r’, ‘p’ or ‘s’
# first create a prompt and explain
input('what is your name?')
      
# for python to do anything with the result we need to save it in a variable which we can name anything but this is informative
player = input('rock (r), paper (p) or scissors (s)?')

# what did we just do? we used a built-in function in Python to prompt the user to input a letter in the console
# and we assigned the input to a variable called 'player'. the = symbol indicates that what is on the right is assigned to the variable name on the left

# what is a function like input or print? They let us do things with objects that we've made, like the player variable

# Now print out what the player chose:
#print(player)
#print('you chose', player)
# mention object type as string or integer
#print(player, 'vs')
print(player, 'vs', end=' ')


# Second: Computer's Turn
# Use 'randint' function to generate a random number to decide whether the computer has chosen rock, paper or scissors.
# we need to import it from 'random' library
from random import randint
chosen = randint(1,3) # search google for how to use via documentation
#print(chosen)
#print('computer chose',chosen)

# we like to print the letters not numbers. let's say 1 = rock, 2 = paper, 3=scissors
# we can use if statement to assign letters to whatever number that is selected
if chosen == 1: 
  computer = 'r' # 'O'
elif chosen == 2: 
  computer = 'p' #'__'
else: 
  computer = 's' #'>8'

print(computer)
# run a few times to show the random nature of the function
# notice that we are not inside the if statement because we don't use indentation
# a nicer output: 
#print(player, 'vs', computer)

# let's add a code for determining the winner 
# we need to compare the 'player' and 'computer' variables
# explain briefly booleans to compare
if player == computer:
  print('Draw!')
elif player == 'r' and computer == 's':
  print('player wins!')
elif player == 'r' and computer =='p':
  print('Computer wins!')
elif player == 'p' and computer == 'r':
  print('Player wins!')
elif player == 'p' and computer == 's':
  print('Computer wins!')
elif player == 's' and computer == 'p':
  print('Player wins!')
elif player == 's' and computer == 'r':
  print('Computer wins!')
  
# Challenge: Instead of using the letters r, p and s to represent rock, paper and scissors, can you use ASCII art?
# O for rock, __ for paper, and >8 for scissors
# so now change the lines you print the choices of the player and the computer in ASCII art 

#if player == 'r':
#  print('O', 'vs', end=' ')
#elif player == 'p':
#  print('__', 'vs', end=' ')
#else: 
#  print('>8', 'vs', end =' ')
  
if player == 'r':
  print('O', 'vs', computer)
elif player == 'p':
  print('__', 'vs', computer )
else: 
  print('>8', 'vs', computer)


s vs p
Player wins!
>8 vs p

summary

What we learned today:

  • built-in functions like input prompt and print
  • variables
  • numbers and strings
  • libraries and functions like randint
  • if statements

review:

Variables


In [ ]:
name = 'Sara'
year = 2017
# we can check the type of our variable using the type(variable_name) function
print(type(name))
#str is a string: a sequence of characters.

Numbers

You can use Python as a calculator:


In [4]:
7 + 8


Out[4]:
15

In [2]:
7*8


Out[2]:
56

In [3]:
8%7


Out[3]:
1

In [4]:
2**4


Out[4]:
16

Python's order of operations works just like math's:

  • Parentheses
  • Exponents
  • Multiplication and division
  • Addition and subtraction

In [ ]:
16 ** 0.5
16 ** (1/2)
16 ** 1/2

Logic

We've talked about how Python handles numbers already. Let's now turn to how it handles inequalities – things that are either true or false.


In [5]:
6 > 0


Out[5]:
True

In [6]:
4 == 6


Out[6]:
False

In [7]:
4 <= 6


Out[7]:
True

In [8]:
4 != 6


Out[8]:
True

Lists

Python has two array-like things. The first is called a "list", which can hold any data types. After the .append() method, explain OOP briefly and why it's useful.


In [9]:
fruits = ['apple', 'banana', 'mango', 'lychee']
print(fruits)


['apple', 'banana', 'mango', 'lychee']

In [11]:
fruits.append('orange')
print(fruits)


['apple', 'banana', 'mango', 'lychee', 'orange', 'orange']

In [12]:
# lists don't need to comprise of all the same type 
misc = [29, 'dog', fruits]

In [13]:
print(misc)


[29, 'dog', ['apple', 'banana', 'mango', 'lychee', 'orange', 'orange']]

In [14]:
print(fruits + fruits)


['apple', 'banana', 'mango', 'lychee', 'orange', 'orange', 'apple', 'banana', 'mango', 'lychee', 'orange', 'orange']

The second is called a "tuple", which is an immutable list (nothing can be added or subtracted) whose elements also can't be reassigned.


In [15]:
tup1 = (1,2)
print(tup1)


(1, 2)

Indexing and Slicing


In [ ]:
#indexing in Python starts at 0, not 1 (like in Matlab or Oracle)
print(fruits[0])

In [ ]:
print(fruits[1])

In [ ]:
# strings are just a particular kind of list
s = 'This is a string.'

In [ ]:
print(s[0])

In [ ]:
# use -1 to get the last element
print(fruits[-1])

In [ ]:
print(fruits[-2])

In [ ]:
# to get a slice of the string use the : symbol
print(s[0:4])

In [ ]:
print(s[:4])

In [ ]:
print(s[4:7])

In [16]:
print(s[7:])
print(s[7:len(s)])


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-ca10691ae8a9> in <module>()
----> 1 print(s[7:])
      2 print(s[7:len(s)])

NameError: name 's' is not defined

For Loops


In [17]:
nums = [23, 56, 1, 10, 15, 0]

In [ ]:
# in this case, 'n' is a dummy variable that will be used by the for loop
# you do not need to assign it ahead of time

for n in nums:
    if n%2 == 0:
        print('even')
    else:
        print('odd')

In [ ]:
# for loops can iterate over strings as well
vowels = 'aeiou'
for vowel in vowels:
    print(vowel)

Functions


In [18]:
# always use descriptive naming for functions, variables, arguments etc.
def sum_of_squares(num1, num2):
    """
    Input: two numbers
    Output: the sum of the squares of the two numbers
    """
    ss = num1**2 + num2**2
    return(ss)

# The stuff inside """ """ is called the "docstring". It can be accessed by typing help(sum_of_squares)

In [ ]:
print(sum_of_squares(4,2))

In [19]:
# the return statement in a function allows us to store the output of a function call in a variable for later use
ss1 = sum_of_squares(5,5)
print(ss1)


50

Useful Packages


In [ ]:
# use a package by importing it, you can also give it a shorter alias, in this case 'np'
import numpy as np
array = np.arange(15)
lst = list(range(15))
print(array)
print(lst)

In [ ]:
print(type(array))
print(type(lst))

In [ ]:
# numpy arrays allow for vectorized calculations
print(array*2)
print(lst*2)

In [ ]:
array = array.reshape([5,3])
print(array)

In [ ]:
# we can get the mean over all rows (using axis=1)
array.mean(axis=1)

In [ ]:
# max value in each column
array.max(axis=0)

In [23]:
import pandas as pd

In [24]:
# this will read in a csv file into a pandas DataFrame
# this csv has data of country spending on healthcare
data = pd.read_csv('health.csv', header=0, index_col=0, encoding="ISO-8859-1")

In [25]:
# the .head() function will allow us to look at first few lines of the dataframe
data.head()


Out[25]:
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
Total expenditure on health as percentage of GDP (gross domestic product)
Abkhazia NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Afghanistan NaN NaN NaN NaN NaN NaN NaN 5.7 6.8 6.4 6.6 6.8 7.3 7.0 7.6 7.6
Akrotiri and Dhekelia NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Albania 2.6 4.0 4.8 5.3 5.8 6.4 6.0 6.3 6.2 6.9 6.8 6.7 6.9 6.7 6.9 6.5
Algeria 4.2 3.8 4.1 4.1 3.9 3.5 3.8 3.9 3.7 3.4 3.1 3.1 3.5 3.7 4.6 4.2

In [26]:
# by default, rows are indicated first, followed by the column: [row, column]
data.loc['Canada', '2008']


Out[26]:
10.300000000000001

In [27]:
# you can also slice a dataframe
data.loc['Canada':'Denmark', '1999':'2001']


Out[27]:
1999 2000 2001
Total expenditure on health as percentage of GDP (gross domestic product)
Canada 8.9 8.8 9.3
Cape Verde 4.5 4.6 5.0
Cayman Islands NaN NaN NaN
Central African Republic 3.5 3.8 3.8
Chad 5.9 6.3 6.0
Channel Islands NaN NaN NaN
Chile 8.2 8.3 8.4
China 4.5 4.6 4.6
Christmas Island NaN NaN NaN
Cocos Island NaN NaN NaN
Colombia 9.3 7.3 7.3
Comoros 3.2 2.9 2.3
Congo, Dem. Rep. 4.3 4.9 4.4
Congo, Rep. 3.1 2.1 2.4
Cook Is 3.5 3.4 4.6
Costa Rica 6.2 6.5 7.1
Cote d'Ivoire 5.6 5.1 4.0
Croatia 7.3 7.8 7.2
Cuba 6.0 6.1 6.3
Cyprus 5.6 5.8 5.8
Czech Republic 6.3 6.3 6.4
Czechoslovakia NaN NaN NaN
Denmark 9.0 8.7 9.1

In [28]:
%matplotlib inline
import matplotlib.pyplot as plt

In [29]:
# the .plot() function will create a simple graph for you to quickly visualize your data
data.loc['Denmark'].plot()
data.loc['Canada'].plot()
data.loc['India'].plot()
plt.legend(loc='best')
plt.savefig("countries_healthexpenditure.png")


Out[29]:
<matplotlib.legend.Legend at 0x1bdd8cb7160>

Guessing game

if we have extra time, we can play another game:


In [ ]:


In [1]:
import random

number = random.randint(1, 10)
tries = 0
win = False # setting a win flag to false


name = input("Hello, What is your username?")
print("Hello " + name + "." )

question = input("Would you like to play a game? [Y/N] ")
if question.lower() == "n": #in case of capital letters is entered
    print("oh..okay")
    exit()
elif question.lower() == "y":
    print("I'm thinking of a number between 1 & 10")

while not win:       # while the win is not true, run the while loop. We set win to false at the start therefore this will always run
    guess = int(input("Have a guess: "))
    tries = tries + 1
    if guess == number:
        win = True    # set win to true when the user guesses correctly.
    elif guess < number:
        print("Guess Higher")
    elif guess > number:
        print("Guess Lower")
# if win is true then output message
print("Congrats, you guessed correctly. The number was indeed {}".format(number))
print("it had taken you {} tries".format(tries))


Hello Sara.
I'm thinking of a number between 1 & 10
Guess Higher
Guess Higher
Guess Higher
Guess Higher
Guess Higher
Congrats, you guessed correctly. The number was indeed 10
it had taken you 6 tries

In [ ]: