# Introduction to Python (part 2)¶

(note: This notebook is running Python 3. If you're using Python 2, then some of these won't work for you)

## Review from last week¶

#### The print statement¶

In [ ]:
print("Hello World!")
print("The Sky is blue.")


#### Getting user input¶

In [ ]:
user_input = input("Enter something here: ")
print("You entered:", user_input)


#### Booleans¶

Booleans are used in computer logic. It is a type that is evaluated as either True or False. The keywords and, or, not are used to evalaute logical expressions, similar to those you'll find in a discrete math class.

In [ ]:
True

In [ ]:
True and False

In [ ]:
False or True

In [ ]:
(not False and not True) or (False or True)


Same thing can be used with 0's and 1's where 0 is False and 1 is True.

In [ ]:
0 and 1


#### Putting them together¶

The function type() will evaluate the parameter and determine the type of the input. We discussed types last week; some the more common ones are strings (str), integers (int), and floats (float).

Make sure what is going in the code below:

In [ ]:
a = "Hello World!"
b = 24892
c = 234.83
d = "24"+str(3)
e = 24 + 1.4

#################

guess_a = input("What type is a? ")
if guess_a == 'str' or guess_a == 'string' or guess_a == 'String':
print("You are right!\n")
else:
print("You are wrong. The type of a is",type(a).__name__,"\n")

guess_b = input("What type is b? ")
if guess_b == 'int' or guess_b == 'integer' or guess_b == 'Integer':
print("You are right!\n")
else:
print("You are wrong. The type of b is",type(b).__name__,"\n")

guess_c = input("What type is c? ")
if guess_c == 'float' or guess_c == 'Float':
print("You are right!\n")
else:
print("You are wrong. The type of c is",type(c).__name__,"\n")

guess_d = input("What type is d? ")
if guess_d == 'str' or guess_d == 'string' or guess_d == 'String':
print("You are right!\n")
else:
print("You are wrong. The type of d is",type(d).__name__,"\n")

guess_e = input("What type is e? ")
if guess_e == 'float' or guess_e == 'Float':
print("You are right!\n")
else:
print("You are wrong. The type of e is",type(e).__name__,"\n")


## Part 2: Loops and Function¶

(again, adapted from Tanya Amert's slides)

### Type: List¶

• Creating
• Accessing, modifying elements
• Appending

A list is a collection of objects. These can by anything including other lists's (called nested). You can store a list in a variable.

In [ ]:
myList = ["apple", 42, 3.14]
myList

In [ ]:
yourList = [7, 'a', myList]
yourList


To access or modify an elemt of a list, use []. The first element's index is 0 and increments from there.

In [ ]:
# What do you think this will return?
myList


To modify the list, we can store a value in the list:

In [ ]:
myList = "banana"
myList

In [ ]:
myList[-1]

In [ ]:
myList[-1] = 'what'
myList


To access a range of elements, use a colon. If you include numbers, those are the start (inclusive) and end (exclusive).

In [ ]:
myList[:1]

In [ ]:
myList[1:]

In [ ]:
anotherList = [0,1,2,3,4,5,6,7,8,9]
# What will show here?
anotherList[3:8]


You can add two lists by using the + sign.

In [ ]:
list1 = ['a','b','c','d','e']
list2 = ['t','u','v','w','x','y','z']
list3 = list1 + list2
list3


To add a single element at the end, use the list method append().

In [ ]:
print(list1)
list1.append('f')
print(list1)


### Loops¶

• for
• while

Why do we want loops? Say you want to return a user's input letter by letter:

In [ ]:
user_word = input("Enter a word: ")
print(user_word)
print(user_word)
print(user_word)
print(user_word)


To accomplish this task, we can find the length of the word using the len function.

In [ ]:
user_word = input("Enter a word: ")

if len(user_word) == 1:
print(user_word)
elif len(user_word) == 2:
print(user_word)
print(user_word)
elif len(user_word) == 3:
print(user_word)
print(user_word)
print(user_word)
elif len(user_word) == 4:
print(user_word)
print(user_word)
print(user_word)
print(user_word)


This is really long, especially if we don't know how long of a word the user will input. This is only one case of many where we want to use loops.

#### for loops (for - each)¶

The for keyword lets us loop over each element in an iterable. The variable between for and in is up to you and is assigned to each element (in this case, a letter in the string) one after another. We can loop over variables as well, as long its an iterable in that there is some mechanism so that we can go 'step through' the variable.

In [ ]:
# THE FOR LOOP (for-each)
user_word = input("Enter a word: ")

for letter in user_word:
print(letter)

In [ ]:
for i in 2:
print(i)


Python also provides the function range which comes in handy when we want specific numbers.

In [ ]:
range(5)

In [ ]:
range(2,5)

In [ ]:
range(1,10,1)

In [ ]:
range(0,10,2)


Putting what we've learned together, we can do something like:

In [ ]:
myList = ["apple","banana","orange"]
for item in range(len(myList)):
print("the fruit at index",item,"is",myList[item])


#### while loops¶

Sometimes you want to repeat something until a certain event. For example, we might want to echo a user until they type a specific word.

In [ ]:
# initializing
response = ""
while response != "stop":
response = input("Please enter a word, or 'stop' to quit: ")
print("You said:",response)

In [ ]:
# What's going wrong here
num = 1
while num <= 0:
num = num+1
print(num)


If you ever run into an infinite loop (usually you'll be able to detect this if your program is taking a long time to run) then just hit ctrl+C to cancel whatever that is going on.

In [ ]:
# Some more practice
num = 1
while num <= 10:
print(num * num)
num = num + 1 # much better


### Functions¶

• defining
• print vs return

We've already seen a bunch of built in functions, such as int, str, input, range, len, etc. We also know about append when working with lists.

We can create our own function using the def keyword.

In [ ]:
def addFunction(a,b):
print(a+b)

In [ ]:
addFunction(8,10)

In [ ]:
def sayHello():
print("Hello")

In [ ]:
sayHello()


If your function only prints, you can't expect to call it and use it in other expressions.

In [ ]:
addFunction(1,2) + addFunction(3,4) # We want to see (1+2) + (3+4)


This is when we use the return keyword to actually return that value. Note that this won't output anything to the screen, but instead will return that result. Lets rewrite our addFunction method and see if we can evaluate multiple of them.

In [ ]:
def addFunction(a,b):
return a+b

In [ ]:
addFunction(1,2) + addFunction(3,4)


### More tools¶

• built in modules
• external packages

Python as a variety of built-in modules, which you can use via the import keyword.

For example, the math module allows us to use functions like sqrt to take the square root of numbers.

To call them, we use modulename.methodname.

In [ ]:
import math
math.sqrt(4)

In [ ]:
math.sin(math.pi) # numerical evaluations usually comes with errors; in this case e-16 is about 0


For external packages, you'll have to download them from an outside source. A few useful packages are

In [ ]: