Lab 2 Lesson

Introduction to Python, Part 1

Topics:

  • Values and Types
  • Variables
  • Operators
  • User Input
  • Changing Data Types
  • Exception Handling
  • Control Flow

For a more in-depth discussion of these topics, read chapters 2 & 3 of Python for Everybody.

Python for Everybody

Python for Everybody is a free online textbook published under the Creative Commons Licence that is a great starter and reference guide for python. Most of the lab excersises will be based on sections of Python for Everybody - in fact, its a great starting reference and could contain hints to solving every excersise, should you get stuck. It breaks down the basics of python and programming as a whole, as many of the concepts we'll cover talking about python apply to almost every programming language. The book itself is availible for purchase if you're really interested in a print copy, but it available as a PDF and epub from the writer for free here. Some sections of Python for Everybody have been adapted from another book, How to think like a Computer Scientist: Learning with Python by Allen Downey, Jeff Elkner and Chris Meyers. This book is also available for free online here.

Values and Types

  • A value is one of the basic things a program works with, like a letter or a number.
  • Values are the nouns of Python programs.
In [ ]:
print(4)
  • Values have a type
  • The first step in understanding Python programming is understanding the different types.
  • We can use the type() function to ask Python to tell what type something is.
In [ ]:
type(4)
  • So what is Python telling us about the value 4?

Type: Integers

  • Python has a type, called int, that is used for representing integer numbers.
In [ ]:
# regular numbers are ints
print(4) 
print(type(4))

# negative numbers are ints
print(-1) 
print(type(-1))

# Even big numbers are ints
print(20928375403298570293847503984570938457)
print(type(20928375403298570293847503984570938457))
  • Be careful when writing big numbers, you can't write them in the way humans write them!
In [ ]:
print(1,000,000, sep=',')
In [ ]:
# European style
print(1.000.000)
  • The computer is very very specific about how things are written.
  • Get used to lots of error messages.
  • Pay attention to every word and every character you type!
  • Like learning to see the Matrix.

Type: Floating Point numbers

  • But what about non-integer numbers?
  • What would be a non-integer number?
  • Python has a type, called float, that is used for representing fractional numbers.
In [ ]:
print(3/4)
In [ ]:
type(3/4)
In [ ]:
type(0.75)
In [ ]:
type(3.1419764565468465465465465465165468484684)

Type: Strings

  • Even though everything is a number in the computer world...
  • The purpose of Python is to make the computer world more humane.
  • Often we need to deal with textual data so we use the string type!
  • The syntax for strings is double (") or single (') quotes.
In [ ]:
print("hello world")
In [ ]:
print(hello world)
In [ ]:
type("Hello World")
In [ ]:
type('Hello World')
  • Note: You can't mix and match quotes!
In [ ]:
print("Hello world')
  • Most people use double quotes because then they don't have apostrophe issues.
In [ ]:
print('I can','t even!')
In [ ]:
print("I can't even, \n either!")

Type: Boolean

  • Python has a data type for True and False
  • A boolean is either True or False
In [ ]:
# Literal true data type, notice how it turns green
True
In [ ]:
# checking the type of True
type(True)
In [ ]:
# Literal false data type, notice how it turns green
False
In [ ]:
# checking the data type of False
type(False)

Variables

  • A variable is a name that refers to a value, so we don't have to literally type the value all the time.
  • We assign different types of data to variables.
In [ ]:
message = "Hello, what a wonderful Thursday morning."
number = 3
pi = 3.1415926535897931
  • This code creates three variables and assigns them different data types.
  • The type of a variable depends upon the value it refers to.
In [ ]:
type(message)
In [ ]:
type(number)
In [ ]:
type(pi)

Variable Names and Python Keywords

  • There are rules and conventions for naming variables in Python.
  • Rules:
    • Variable names cannot begin with numbers.
    • Variable names cannot contain spaces.
    • Variable names are case sensitive.
    • Variable names cannot be one of the Python keywords
and       del       from      None      True
as        elif      global    nonlocal  try
assert    else      if        not       while
break     except    import    or        with
class     False     in        pass      yield
continue  finally   is        raise
def       for       lambda    return
In [ ]:
# don't use keywords for variable names
and = "hello"
In [ ]:
# long names are good for reading, but are long
this_is_a_good_variable_name = 4
print(this_is_a_good_variable_name)
In [ ]:
# don't use spaces!
Hello number for = 4
print(Where are you @)
In [ ]:
# don't get too funky with weird characters
what@isup? = 4
In [ ]:
clown = "🤡" 
In [ ]:
print(clown)

Operators

  • The Python programming language could be treated as a very fancy or complicated calculator.
  • All of the mathematical operators you know and love are available in Python
    • Addition: +
    • Subtraction: -
    • Multiplication: *
    • Division: /
    • Modulus: %
In [ ]:
# addition
5 + 3
In [ ]:
# subraction
5 - 3
In [ ]:
# Works with variables
a = 5
b = ((3 + a) - 235345)

a * b // 5
In [ ]:
# Modulus is for calculating the remainder
remainder = 5 % 3
print(remainder)

String Operators

  • You can use these mathematical operators on string types
In [ ]:
# Make strings instead of numbers
a = 'School of Computing'
b = 'and Information'

a + " " + b
  • Mixing up datatypes is a common bug in your code.
  • Sometimes Python will figure out what you were trying to do...
  • Other times it won't
In [ ]:
a = str(5)
b = '3'

a + b

User Input

  • If you want the user (you) to give your program information, you can use the input() function.
  • Input will display a text entry box when you run the cell and save it to a variable (if you assign a variable to the input function).
  • Put a string inside the function to create a prompt.
In [ ]:
# as for the user's name and put it in a variable called name
name = input("What is your name?")
In [ ]:
# now print the contents of the variable called name
print(name)
In [ ]:
 
In [ ]:
type(name)

Changing Data Types

  • If you want to do mathematical operations on your data, make sure your data is of the right type
  • You can't add a string to an integer.
  • You can't divide a float by a string.
In [ ]:
# What will happen when we run this?
"5" + 5
  • Use the int() function to transform a string into a number
In [ ]:
# store a number as a string
number = "5"
print(type(number))
In [ ]:
# transform number from a string to an int
number = int(number)
print(type(number))
  • Use the str() function to coerce your data into a string
In [ ]:
# transform a number into a string representation
number = 5
print(type(number))

number = str(number)
print(type(number))
  • Use the float() function to transform decimal numbers
In [ ]:
# transform a number into a string representation
number = "5.5"
print(type(number))

number = float(number)
print(type(number))
print(number)
  • The input() function always gives you data of type string
  • If the data you are getting is a number, you got to transform it
  • Make sure to transform to the right data type!
In [ ]:
# try converting a string containing a decimal to an integer
number = input("Input a decimal number:")
print(type(number))
number = int(number)
print(type(number))
print(number)
In [ ]:
# convert a decimal to a float
number = input("Input a decimal number:")
print(type(number))
number = float(number)
print(type(number))
print(number)

Control Flow

  • We can use logical operators (<, >, !=, is, is not) and conditional expressions (if, else, elif) control the flow of execution
  • if true then do this, else do that
  • We use boolean expressions (True, False) to answer Yes/No questions and decide which path to execute
In [ ]:
# testing for equality
5 == 5
In [ ]:
# Does five equal six?
5 == 6
In [ ]:
6 != 5
  • Note the double equals sign, if we had one equals we would be a variable assignment.
  • == is called a comparison operators and there are many others
    x != y               # x is not equal to y
    x > y                # x is greater than y
    x < y                # x is less than y
    x >= y               # x is greater than or equal to y
    x <= y               # x is less than or equal to y
    x is y               # x is the same as y
    x is not y           # x is not the same as y
    
  • These allow you to express logical operations in your programs.
x > 0 and x < 10
  • This expression is true only when "the variable x is greater than zero AND less than 10"
In [ ]:
# the variable x is greater than zero AND less than 10
x = 5
x > 0 and x < 10
In [ ]:
# the variable x is greater than zero AND less than 10
x = 50
x > 0 and x < 10
In [ ]:
# the variable x is greater than zero AND less than 10
x = 50
x > 0 or x < 10

Conditional execution

  • use the if, else, and elif statements to steer the direction of your program
In [ ]:
# test to see if x is positive and print if it is
x = 5
if x > 0:
    print("x is a positive number")
In [ ]:
# test to see if x is positive and print if it is
x = -5
if x > 0:
    print("x is a positive number")
  • Notice, nothing printed because the condition, x > 5 was false
In [ ]:
if 5 == 5:
    print("yup")
    print("Yup, five is five")
In [ ]:
if 5 == 6:
    print("five is six, huh?")
    print("this won't run")
    
# This line executes no matter what
print("I am done.")
  • use != to say "not equals"
In [ ]:
# testing not equality
if 5 != 6:
    print("five is six, huh?")
    print("this won't run")

# This line executes no matter what
print("I am done.")
  • No print because 5 doesn't equal 6
In [ ]:
if 5 > 6:
    print("five is greater than six, what?")
    print("hi")
  • Works with variables too!
In [ ]:
x = 5
y = 6

if x < y:
    print(x, "is less than", y)

Alternative execution

  • if true do this, else do that
In [ ]:
# check to see if x is even or odd
x = 20
if (x % 2) == 0: # using the modulo operator
    print("x is even")
else:
    print("x is odd")
In [ ]:
# check to see if x is even or odd
x = 21
if (x % 2) == 0: # using the modulo operator
    print("x is even")
else:
    print("x is odd")
In [ ]:
# check to see if x is even or odd
x = 0
if (x % 2) == 0: # using the modulo operator
    print("x is even")
else:
    print("x is odd")

Nested Conditionals

  • You can put conditional statements inside of other conditional statements
  • This lets you compose more complex logic in your programs
In [ ]:
x = 5
y = 5

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')
In [ ]:
x = 50
y = 5

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')
In [ ]:
x = 5
y = 50

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')

Chained Conditionals

  • If there are more than two conditions you want to check use elif (else if)
  • Use there if there are more than two branches in your logic
In [ ]:
# multiple conditions


age = int(input("Give me your age"))

if 0 < age < 1:
    print("baby")
elif 1 <= age <= 3:
    print("toddler")
elif 3 <= age <= 9:
    print("kid")
elif 10 <= age <= 12:
    print("Tween")
elif 13 <= age <= 17:
    print("Teen")
elif 18 <= age < 120:
    print("Adult, welcome to misery.")
else:
    print("No one can live that long!")
    

Exception Handling

  • Sometimes you have a decimal number and you want to do something integer-y or you have a number as a string and not an int or float datatype
  • If you try and do an operation on the data you will get an error
In [ ]:
# Python won't like this
string_decimal_number = "5.5"
int(string_decimal_number)
In [ ]:
# but this will work
string_decimal_number = "5.5"
float(string_decimal_number)

You can use the try/except statements to "catch" your error.

In [ ]:
# prompt the user for a number
number = input("Input a number:")
try:
    int_number = int(number)
    print("I am an integer number")
except:
    float_number = float(number)
    print("I am a floating point number")

Let's look at that code above again.

What try does is say to Python: "This code might cause an error and say something's wrong. I know that, so let me handle it." If an error does happen inside a try block, it'll jump to except and start running that code.

So, above, when you input a number, it'll try to convert it into an integer. But, not all numbers are integers. If Python gets an error, it doesn't freak out and crash. It just jumps to the except block.

Run that code block above again. Enter integers and non-integers. How can you still break it?


Putting it all together

The code cell below contains the code for a whole program that combines all of the topics we learned about. Try running it a few times and see what happens!

In [ ]:
# get the age and animal type from the user
age = input("Input Age:")
kind = input("Cat, Dog, Human")

# make age into an number
try:
    age = int(age)
except:
    age = float(age)

if kind == "Human" or kind == "human": # check for caps
    if 0 < age < 1:
        print("baby")
    elif 1 <= age <= 3:
        print("toddler")
    elif 3 <= age <= 9:
        print("kid")
    elif 10 <= age <= 12:
        print("Tween")
    elif 13 <= age <= 17:
        print("Teen")
    elif 18 <= age <120:
        print("Adult, welcome to misery.")
    else:
        print("No one can live that long!")
        
elif kind == "Dog" or kind == "dog": 
    if 0 < age <= 1:
        print("Puppy")
        print(age * 7, "human years.")
    else:
        print("Adult")
        print(age * 7, "human years.")

elif kind == "Cat" or kind == "cat":
    if 0 <= age <= 1:
        print("Innocent Kitten")
        print("???", "human years.")
    else:
        print("Evil Beast")
        print("???", "human years.")
else:
    print("I don't know that animal.")

We are done, bye yall