Python Exercises

Note: Exercises in gray are those that appear in the Introduction. Feel free to skip these if you have already completed them.

Getting Started

Entering Code

  1. What is 126544 squared? (Exponentiation is denoted `**`, i.e. $ 2^3 $ is `2**3` in Python).
  2. What is 5 divided by 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?
  4. Write some code to calculate the number of minutes in a year with a comment that describes what your code does.
  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?

Data Types and Variables

Strings and Numbers

  1. Define two variables, j and k, with values 37 and 52 respectively.
    • What is the sum of `j` and `k`? The product? Write code for each of these in the **editor window**, and run with the keyboard shortcut (refer back to Section 1. Entering Code).
    • Now re-assign `j` and `k` to have the vales 8 and 3 respectively. Re-use your code from the editor to determine their sum and product.
  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.
    • Variables allow help you to more easily account for a variety of situations. For example, 2020 happens to be a leap year. How does that change your code? Make a new variable that accounts for the number of days in a leap year. You can now easily change your code to print the number of minutes in a leap year as opposed to a non-leap-year.
  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
  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).
    • For this exercise, define 5-10 numbers as variables.
      num1=...
      num2=...
      num3=...
      num4=...
      num5=...
      num6=...
      num7=...
      num8=...
      num9=...
      num10=...
    • Use a single print statement to print all of the even numbers out of your newly defined variables with the following statement, "These are my even numbers:".
    • The + 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).
In [1]:
print("work"+"shop")
print("3"+"7")
workshop
37

Lists

  1. Create a list of:

    • your favorite color (str)
    • your two favorite holidays (list)

      For example: ["red", ["Halloween", "New Years"]]

  2. Then append the number of pets you have (int) as a new list item. Print your new list.
  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:
    • Number of hours in a day
    • Number of minutes in an hour
    • List that includes the number of days in a normal year as well as the number of days in a leap year

Indexing

  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
  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"]]
    • What is the fifteenth letter of the alphabet?
    • What is the code for the twenty-third letter of the alphabet?
    • What is the fourth letter of the code for the eighth letter of the alphabet?
  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.

  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?",
    "We went to the zoo."
    ]
    • Can you create the following sentence using only elements from this list? sentence = "The boy yells loudly." In other words, create and print this sentence without typing any new bits of text.

      • Hint: The .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."
      • Hint Hint: Use the .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."
    • Can you create a "MyName" variable (str) that stores your name using only elements from the sentences list above? In other words, create and print your name without typing any new bits of text.

Flow Control

Conditions and Booleans / Conditional Statements

  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.”)
  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)
  3. 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
    • Write a conditional statement that determines whether or not the year is a leap year. Print messages that tell the user whether or not it is a leap year as well as the number of minutes in the year.
         #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!")
    • Now change the DaysInYear variable. Does your code perform as expected? What happens if you set your variable equal to a number that isn't 365 or 366? Does this make any sense? Change your statements or add clauses to account for more entries than just these two.
  4. 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.

    • Does your word not contain any text at all?
    • Does your word contain the letter "i" or the letter "b"?
    • Is your word longer than 5 characters?
    • Did you simply use "word"?
    • Did your word not satsify any of the above conditions?
      • For example:
        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...

For Loops

In [2]:
#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)
[['blue', 4], ['yellow', 6], ['red', 3], ['green', 5]]

(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?

For Loops with Conditionals

In [3]:
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)
[[95, 'A'], [90, 'A'], [66, 'D'], [83, 'B'], [71, 'C'], [78, 'C'], [93, 'A'], [81, 'B'], [87, 'B'], [81, 'B']]
  1. Referencing the above code, why do I only specify `score>=80` etc. in the `elif` statements? Can any of these conditionals be simplified?
  2. How many numbers between 1 and 100 are divisible by 7?
  3. Make a new list of NATO codes keeping only those that use the letter "a" in their *code*.
  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]
    • Knowing that 2020 is a leap year and that leap years only occur every four years, iterate through the list. Use conditionals to add all leap years to a separate list (Hint: use the modulo function to determine which years are leap years). Print your new list of leap years.

Breaks

  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.

More Data Types

Comprehensions

In [4]:
squaresdict={k:k**2 for k in range(1,16)}
print(squaresdict)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}

1. Considering the code above, write a list comprehension to create a list of just the values (i.e. the squares) from `squaresdict`.

Pseudocode and Comments

Pseudocode

In [5]:
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.
  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.)

Comments

In [6]:
#Example:

#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.

User-defined Functions

  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()` to create a list sorted from low to high values.

  2. Test your function with the lists below:

In [7]:
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