Note: Exercises in gray are those that appear in the Introduction. Feel free to skip these if you have already completed them.
1. What is 126544 squared? (Exponentiation is denoted `**`, i.e. $ 2^3 $ is `2**3` in Python).
126544**2
2. What is 5 divided by 0?
5/0
3. Mathematical operations in Python follow the standard order of operations. Parentheses in the wrong place can cause hard-to-find errors in your code. What is the difference between 6+5*10
and (6+5)*10
?
#Here we use "print" statements so that both answers will be displayed.
print(6+5*10)
print((6+5)*10)
4. Write some code to calculate the number of minutes in a year with a comment that describes what your code does.
#My code multiplies the days in a year by the hours in a day by the minutes in an hour.
365*24*60
5. What is the area of a square with a side length of 7? What is the volume of a cube with the same edge length?
#square
7**2
#cube
7**3
1. Define two variables, j and k, with values 37 and 52 respectively.
j=37
k=52
j=37
k=52
#sum
print(j+k)
#product
print(j*k)
j=8
k=3
#sum
print(j+k)
#product
print(j*k)
2. Now let us calculate the number of minutes in a year again, this time using variables for each unit of time. Instead of a comment, print a statement that describes what your code does.
DaysInYear=365
HoursInDay=24
MinutesInHour=60
print("My code multiplies the DaysInYear*HoursInDay*MinutesInHour.")
print(DaysInYear*HoursInDay*MinutesInHour)
DaysInNormalYear=365
DaysInLeapYear=366
HoursInDay=24
MinutesInHour=60
MinutesInNormalYear = DaysInNormalYear*HoursInDay*MinutesInHour
MinutesInLeapYear = DaysInLeapYear*HoursInDay*MinutesInHour
print(MinutesInNormalYear)
print(MinutesInLeapYear)
3. Define the variables below. Print the types of each variable. What is the sum of your variables? (Hint: use a type conversion function.) What datatype is the sum?
num=23
textnum="57"
decimal=98.3
num=23
textnum="57"
decimal=98.3
print(type(num))
print(type(textnum))
print(type(decimal))
MySum=num+int(textnum)+decimal
print(MySum)
print(type(MySum))
4. You can use the print function to print multiple variables of different types on a single line. This can be done by using comma to separate variables within the parentheses of the print function. For example: print(variable1, variable2).
You can also print raw values that have not been assigned variables. For example, print("This is variable 1: ", 67)
.
num1 = 58
num2 = 45
num3 = 95857
num4 = 1
num5 = 99
num6 = 68
num7 = 2
print
statement to print all of the even numbers out of your newly defined variables with the following statement, "These are my even numbers:". print("These are my even numbers:", num1, num6, num7)
+
operator in Python works with strings variables as well as numeric types - but it simply concatenates strings together one after the other. Using +
and the example below, write your output as a single complete sentence. (Hint: you'll probably need to use at least one type conversion function).print("work"+"shop")
print("3"+"7")
print("The even numbers out my newly defined variables are " + str(num1) + ", " + str(num6) + ", and " + str(num7) + ".")
1. Create a list of:
your two favorite holidays (list)
For example:
["red",["Halloween","New Years"]]
MyList = ["red",["Halloween", "New Years"]]
2. Then append the number of pets you have (int) as a new list item. Print your new list.
MyList.append(3)
print(MyList)
3. Create a list that includes the number of days in a normal year as well as the number of days in a leap year. Now create a separate list that includes the number of hours in a day as well as the number of minutes in an hour. Append your first list to your second list. Your final list should look something like this:
list1=[365, 366]
list2=[24, 60]
list2.append(list1)
print(list2)
1. Try to use indexing to get the tenth digit of `my_pi` as defined below. Does it work as defined? Do we need to change the variable somehow?
my_pi=3.141592653589793
my_pi=3.141592653589793
print(my_pi[10])
my_pi=3.141592653589793
my_pi=str(my_pi)
print(my_pi[10])
#Note that we access the 10th digit using the number 10, rather than 9. This is because there is
#a decimal point at my_pi[1].
2. Below is a list of lists containing the NATO phonetic codes for each letter of the alphabet. Each list within `nato` contains a letter of the alphabet and its corresponding code.
nato = [["A", "Alfa"],
["B", "Bravo"],
["C", "Charlie"],
["D", "Delta"],
["E", "Echo"],
["F", "Foxtrot"],
["G", "Golf"],
["H", "Hotel"],
["I", "India"],
["J", "Juliett"],
["K", "Kilo"],
["L", "Lima"],
["M", "Mike"],
["N", "November"],
["O", "Oscar"],
["P", "Papa"],
["Q", "Quebec"],
["R", "Romeo"],
["S", "Sierra"],
["T", "Tango"],
["U", "Uniform"],
["V", "Victor"],
["W", "Whiskey"],
["X", "X-ray"],
["Y", "Yankee"],
["Z", "Zulu"]]
nato = [["A", "Alfa"],
["B", "Bravo"],
["C", "Charlie"],
["D", "Delta"],
["E", "Echo"],
["F", "Foxtrot"],
["G", "Golf"],
["H", "Hotel"],
["I", "India"],
["J", "Juliett"],
["K", "Kilo"],
["L", "Lima"],
["M", "Mike"],
["N", "November"],
["O", "Oscar"],
["P", "Papa"],
["Q", "Quebec"],
["R", "Romeo"],
["S", "Sierra"],
["T", "Tango"],
["U", "Uniform"],
["V", "Victor"],
["W", "Whiskey"],
["X", "X-ray"],
["Y", "Yankee"],
["Z", "Zulu"]]
# 3. - 15th letter is: ["O", "Oscar"]
print(nato[14][0])
# 4. - 23rd letter is: ["W", Whiskey]
print(nato[22][1])
# 5. - 8th letter is: ["H", "Hotel"]
print(nato[7][1][3])
3. Let's perform some more minutes-in-year calculations . Using the lists you created above, calculate and print the number of minutes in a normal year. Now calculate and print the number of minutes in a leap year. Print your results.
TimeList=[24, 60, [365, 366]]
MinutesInNormalYear=TimeList[0]*TimeList[1]*TimeList[2][0]
print(MinutesInNormalYear)
MinutesInLeapYear=TimeList[0]*TimeList[1]*TimeList[2][1]
print(MinutesInLeapYear)
4. Consider the following list of sentences:
Sentences = [
"I went to The Ohio State University",
"Add just a bit more.",
"Cars drive quickly.",
"He heard yells outside.",
"What is your name?",
"Bob was very exasperated.",
"Give me the keys.",
"Boy oh boy am I glad to see you!",
"Students in the hallway whispered loudly.",
"You're learning Python!",
"What is the capital of Florida?"
]
sentence = "The boy yells loudly."
In other words, create and print this sentence without typing any new bits of text..split()
function can be used to split a string into a list of words. For example: str = "I want pizza."
Using the following code, you can split the sentence str
into a list of words separated by spaces: list = str.split(" ")
. This command uses whitespaces (" ")
to separate words into a list, leading to the following output: ["I", "want", "pizza."]
. You can now use list indexing to easily access words within a sentence. For example, list[2]
would output the word "pizza."
.join()
function to join elements of a list into a string. Let's use our earlier example, where list=["I", "want", "pizza."]
. Here, the command " ".join(list)
glues all of the elements in list
together with whitespaces (" "
) between them. As a result, using the command str = " ".join(list)
will bring us back to where we started! str = "I want pizza."
Sentences = [
"I went to The Ohio State University",
"Add just a bit more.",
"Cars drive quickly.",
"He heard yells outside.",
"What is your name?",
"Bob was very exasperated.",
"Give me the keys.",
"Boy oh boy am I glad to see you!",
"Students in the hallway whispered loudly.",
"You're learning Python!",
"What is the capital of Florida?"
]
#Split the sentences with the required words into lists
#so that we can access each word individually.
SentenceList1 = Sentences[0].split(" ")
SentenceList2 = Sentences[7].split(" ")
SentenceList3 = Sentences[3].split(" ")
SentenceList4 = Sentences[8].split(" ")
#Declare the required words in each of those lists as variables
#so that we can use them below to glue together a new sentence.
the = SentenceList1[3]
boy = SentenceList2[2]
yells = SentenceList3[2]
loudly = SentenceList4[-1]
#Make a new list from the required words
NewSentenceList = [the, boy, yells, loudly]
#join the required words from the above list into a sentence string
NewSentence = " ".join(NewSentenceList)
print("Combined sentence: ", NewSentence)
sentences
list above? In other words, create and print your name without typing any new bits of text.Sequence = "The boy yells loudly"
Sentences = [
"I went to The Ohio State University",
"Add just a bit more.",
"Cars drive quickly.",
"He heard yells outside.",
"What is your name?",
"Bob was very exasperated.",
"Give me the keys.",
"Boy oh boy am I glad to see you!",
"Students in the hallway whispered loudly.",
"You're learning Python!",
"What is the capital of Florida?",
"We went to the zoo."
]
MyName = Sentences[1][4]+Sentences[2][1]+Sentences[8][5]
print("My name: ", MyName)
1. Write an if statement that prints a message if a person is old enough to get a driver’s license (teenagers can get their driver’s licenses at age 16). Next, add in an else statement that gives a different message.
#Template:
age = <your choice of age>
if <condition using age>:
print(“you are old enough to get a driver’s license.”)
#True Example
age = 18
if age>=16:
print("you are old enough to get a driver’s license.")
else:
print("you are NOT old enough to get a drivers license")
#False Example
age = 14
if age>=16:
print("you are old enough to get a driver’s license.")
else:
print("you are NOT old enough to get a drivers license")
2. Using indexing, write a conditional that print a word only if it ends with the letter 'e'.
#Template:
testword=<your choice of word>
if <condition using testword>:
print(testword)
#True Example
testword = "base"
if testword[-1]=="e":
print(testword)
#False Example
testword = "cat"
if testword[-1]=="e":
print(testword)
2. Now that we've learned conditionals, we can more easily account for a wide range of circumstances. Let's go back to our minutes-in-a-year example. Define the following variables:
DaysInYear=365
HoursInDay=24
MinutesInHour=60
#Template:
if <condition to determine if a day is a leap year>:
print(<Minutes In Year calculation>)
print("It's a leap year!")
else:
print(<Minutes In Year calculation>)
print("It's not a leap year!")
DaysInYear=365
HoursInDay=24
MinutesInHour=60
if DaysInYear==366:
print(DaysInYear*HoursInDay*MinutesInHour)
print("It's a leap year!")
else:
print(DaysInYear*HoursInDay*MinutesInHour)
print("It's not a leap year!")
#example input
DaysInYear=10000
HoursInDay=24
MinutesInHour=60
if DaysInYear==366:
print(DaysInYear*HoursInDay*MinutesInHour)
print("It's a leap year!")
elif DaysInYear==365:
print(DaysInYear*HoursInDay*MinutesInHour)
print("It's not a leap year!")
else:
print(DaysInYear*HoursInDay*MinutesInHour)
print("It's a different kind of year entirely!")
3. Pick any word and declare it as a variable. Write a conditional statement (if
, elif
, else
) that checks your word for the conditions below. Print different messagess that describe the word if it satisfies any of the individual conditions.
testword = "google"
if testword <condition concerning testword>
print(<message describing why that word satisfied the condition>)
elif testword <condition concerning testword>
print(<message describing why that word satisfied the condition>)
#etc...
checkWord = "google"
if checkWord == "":
print("I just didn't feel like playing this game.")
elif "i" in checkWord or "b" in checkWord:
print("My word is not blank and contains i or b.")
elif len(checkWord) > 5:
print("My word is long but does not contain i or b.")
elif checkWord == "word":
print("I am lazy and picked an obvious word.")
elif checkWord in ["here", "is", "a", "short", "list", "of", "words"]:
print("My word doesn't have i or b.")
print("It's not long, but it is in this list.")
print("Also, I did not pick the most obvious word")
else:
print("I'm clever and didn't satisfy any of the conditions.")
#Nesting loops - indentation is key!
listOfWords = ["blue", "yellow", "red", "green"]
newList = [] #initialize an empty list
for color in listOfWords:
numLetters = 0 #resets to zero each time the loop runs
for letter in color:
numLetters += 1
temporaryList = [color, numLetters]
newList.append(temporaryList)
print(newList)
(Un-numbered Exercise) How could we write the code above with fewer lines? Is there a simpler way to find the length of each word?
#we can skip the loop that iterates through all of the letters in each word by using the
#len() function. len() counts the number of characters in a string or
#the number of elements in a list.
listOfWords = ["blue", "yellow", "red", "green"]
newList = []
for color in listOfWords:
newList.append([color, len(color)])
print(newList)
scores=[95,90,66,83,71,78,93,81,87,81]
grades=[]
for score in scores:
if score>=90:
grade="A"
elif score>=80:
grade="B"
elif score>=70 and score<80:
grade="C"
elif score>=60 and score<70:
grade="D"
else:
grade="F"
grades.append([score,grade])
print(grades)
1. Referencing the above code, why do I only specify `score>=80` etc. in the `elif` statements? Can any of these conditionals be simplified?
# elif score>=70 and score<80:
# grade="C"
# elif score>=60 and score<70:
# grade="D"
#Neither or these statements require their 'and' portions. Conditional statements run
#from top to bottom, meaning that once one condition is satisfied, none of the statements
#below that statement will be examined. This makes the 'and score<80', etc. unecessary because any
#numbers above 80 would have satisfied the condition above. Any number that is between 70 and 80
#will not satisfy either of the first two conditions, but will satisfy the third condition.
scores=[95,90,66,83,71,78,93,81,87,81]
grades=[]
for score in scores:
if score>=90:
grade="A"
elif score>=80:
grade="B"
elif score>=70:
grade="C"
elif score>=60:
grade="D"
else:
grade="F"
grades.append([score,grade])
print(grades)
2. How many numbers between 1 and 100 are divisible by 7?
#Once again we can use the modulo (%) function
DivBy7=[]
for i in range(100):
num = i+1 #Python always starts at zero, meaning this loop will iterate through numbers 0-99
if num%7==0:
DivBy7.append(num)
print(DivBy7)
3. Make a new list of NATO codes keeping only those that use the letter "a" in their *code*.
nato=[["A","Alfa"],
["B","Bravo"],
["C","Charlie"],
["D","Delta"],
["E","Echo"],
["F","Foxtrot"],
["G","Golf"],
["H","Hotel"],
["I","India"],
["J","Juliett"],
["K","Kilo"],
["L","Lima"],
["M","Mike"],
["N","November"],
["O","Oscar"],
["P","Papa"],
["Q","Quebec"],
["R","Romeo"],
["S","Sierra"],
["T","Tango"],
["U","Uniform"],
["V","Victor"],
["W","Whiskey"],
["X","X-ray"],
["Y","Yankee"],
["Z","Zulu"]]
newNato=[]
for i in nato:
if "a" in i[1]:
newNato.append(i)
for j in newNato:
print(j)
4. Consider the following list of years:
years=[1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,
2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,
2012,2013,2014,2015,2016,2017,2018,2019,2020]
years=[1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,
2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,
2012,2013,2014,2015,2016,2017,2018,2019,2020]
leapYears=[]
for year in years:
if year % 4 == 0:
leapYears.append(year)
print(leapYears)
1. Use the `choices` function above to generate a random list of 50 numbers in 0-99. Write a loop that will find the sum of only the first 6 even numbers.
from random import choices,seed
#if you set the following seed you should get the same results as this solution!
seed(1234)
test=choices(population=range(100),k=50)
count = 0 #declare a count to help us keep track of how many even numbers we've found so we know when to break
first6even =[] # create a list so we can see which numbers were added to our sum
for i in test:
if i % 2 == 0: # If the number is divisible by two:
count += 1 #add 1 to our count of even numbers found
first6even.append(i) #add our newly found even number to our list of even numbers so that
#we can check them later
if count>=6:
break # once we've found 6, exit the loop
print(sum(first6even)) # What was our sum?
print(first6even) # Do our numbers really add up?
print(test) # Are these really the first 6 even numbers in our list?
squaresdict={k:k**2 for k in range(1,16)}
print(squaresdict)
1. Considering the code above, write a list comprehension to create a list of just the values (i.e. the squares) from `squaresdict`.
#Remember the .keys() function?
#You can use this to get the keys (and thus the values) for each item in your dictionary
squares = [squaresdict[k] for k in squaresdict.keys()]
print(squares)
random_words=["statement", "toy", "cars", "shoes", "ear", "busy",
"magnificent", "brainy", "healthy", "narrow", "join",
"decay", "dashing", "river", "gather", "stop", "satisfying",
"holistic", "reply", "steady", "event", "house", "amused",
"soak", "increase"]
vowels=["a","e","i","o","u","y"]
output=[]
for word in random_words:
count=0
for char in word:
if char in vowels:
count=count+1
if count>=3:
output.append([word,count])
1. Write pseudocode to summarize the code above.
#One potential solution:
#This script creates a list of words that have more than 3 or more vowels.
#Each word is contained in a list with the word itself as well as the number of vowels it contains
#1. define a list of random words
#2. define a list of vowels
#3. declare a new empty list called output that I can use to store my words and vowel counts
#4. iterate through my list of random words
#4a. before checking letters, reset the vowel count to zero for the new word
#4b. iterate through the all f the letters in each word
#4b_1. check each letter to see if it is in the vowel list we defined above.
#If it is in that list, add 1 to the vowel count for that particular word
#4c. once we have checked all letters in the word and counted the vowels,
#check to see if the word has 3 or more vowels
#4d. if it does have 3 or more vowels, add a list
#containing the word and its vowel count to our output list
2. Write pseudocode to check an arbitrary list of numbers, `my_numbers`, to find all even numbers and convert them to odd numbers by adding one. Put the resulting numbers into a new list `my_numbers2`. (Recall `for` loops ,`if` conditions, and the modulo function `%` from Python 1.)
#One potential solution:
#1. Get or define the list my_numbers
my_numbers=list(range(100))
#2. Create an empty list for the new all-odd numbers, called my_numbers2.
#3. Use a loop to iterate through the list of numbers
#3a. For a given number check to see if it is even.
#3b. If the number is even, add 1.
#3c. Append the resulting number to the my_numbers2 list.
1. Use your own pseudocode or the example above as an outline to fill in with Python code. Test your code with the `my_numbers` object defined above.
#1. Get or define the list my_numbers
my_numbers=list(range(100))
#2. Create an empty list for the new all-odd numbers, called my_numbers2.
my_numbers2 = []
#3. Use a loop to iterate through the list of numbers
for num in my_numbers:
#3a. For a given number check to see if it is even.
if num % 2 == 0:
#3b. If the number is even, add 1.
new_num = num + 1
#3c. Append the resulting number to the my_numbers2 list.
my_numbers2.append(new_num)
1. Define a function, `median` to find the median of a list. The median is the middle number of an odd-numbered list or the average of the middle two numbers in an even numbered list. (Hint: Use `sorted(
def median(your_list):
median = 0
n = len(your_list)
your_list = sorted(your_list)
if n % 2 == 1: #if your list has an odd number of values
middle_index = int((n/2) - .5) #Your middle index will be equal to the length of your list, divided by 2
#minus .5 (minus because indices start at 0). Transform this number using int()
#so that it can be used as a list index.
median = your_list[middle_index]
else:
middle_index1 = int(n/2 - 1)
middle_index2 = int((n/2))
median = (your_list[middle_index1] + your_list[middle_index2])/2
#If the list has an even number of values, we need to get the two middle indices (middle_index1 and 2)
#Your median in this situation is the average of the values at these two locations
return median
2. Test your function with the lists below:
data1 = list(range(1,100))
#Normally Distributed Data:
from numpy.random import normal
data2 = normal(loc=0,scale=2,size=100) #scale=2 defines the standard deviation as 2
print(median(data1))
print(median(data2))