Python Exercises (Solutions)

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

In [1]:
126544**2
Out[1]:
16013383936

2. What is 5 divided by 0?

In [2]:
5/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-0106664d39e8> in <module>
----> 1 5/0

ZeroDivisionError: division by zero

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?

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

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

In [ ]:
#square
7**2
In [ ]:
#cube
7**3

Data Types and Variables

Strings and Numbers

1. Define two variables, j and k, with values 37 and 52 respectively.

In [ ]:
j=37
k=52
  • 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). SpyderIDE with code shown below executed
In [ ]:
j=37
k=52

#sum
print(j+k)
#product
print(j*k)
  • 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.
In [ ]:
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.

In [ ]:
DaysInYear=365
HoursInDay=24
MinutesInHour=60

print("My code multiplies the DaysInYear*HoursInDay*MinutesInHour.")
print(DaysInYear*HoursInDay*MinutesInHour)
  • Leap Year:
In [ ]:
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
In [ ]:
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).

  • For this exercise, define 5-10 numbers as variables.
In [ ]:
num1 = 58
num2 = 45
num3 = 95857
num4 = 1
num5 = 99
num6 = 68
num7 = 2
  • 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:".
In [ ]:
print("These are my even numbers:", num1, num6, num7)
  • 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 [ ]:
print("work"+"shop")
print("3"+"7")
In [ ]:
print("The even numbers out my newly defined variables are " + str(num1) + ", " + str(num6) + ", and " + str(num7) + ".")

Lists

1. Create a list of:

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

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

In [ ]:
MyList = ["red",["Halloween", "New Years"]]

2. Then append the number of pets you have (int) as a new list item. Print your new list.

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

  • Number of hours in a day (int)
  • Number of minutes in an hour (int)
  • List that includes the number of days in a normal year as well as the number of days in a leap year (list)
In [ ]:
list1=[365, 366]
list2=[24, 60]
list2.append(list1)

print(list2)

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
In [ ]:
my_pi=3.141592653589793
print(my_pi[10])
  • This error means that you cannot access digits in a float in the same way that you can access characters in a string or indices in a list. You can access individual digits by converting the variable to a string before 'slicing' it into individual elements.
In [ ]:
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"]]
  • 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?
In [3]:
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])
O
Whiskey
e

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.

In [4]:
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)
525600
527040

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?"
]
  • 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."
In [5]:
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)
Combined sentence:  The boy yells loudly.
  • Can you create a "MyName" variable 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.
In [6]:
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)
My name:  jan

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.”)
In [7]:
#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")
you are old enough to get a driver’s license.
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)
In [8]:
#True Example
testword = "base"
if testword[-1]=="e":
    print(testword)
    
#False Example    
testword = "cat"
if testword[-1]=="e":
    print(testword)
base

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
  • 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!")
In [9]:
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!")
525600
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? Do your results make any sense? Change your statements or add clauses to account for more entries than just these two (365 and 366).
In [10]:
#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!")
14400000
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.

  • 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...
In [11]:
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.")
My word is long but does not contain i or b.

For Loops

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

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

For Loops with Conditionals

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?

In [13]:
#    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)
[[95, 'A'], [90, 'A'], [66, 'D'], [83, 'B'], [71, 'C'], [78, 'C'], [93, 'A'], [81, 'B'], [87, 'B'], [81, 'B']]

2. How many numbers between 1 and 100 are divisible by 7?

In [14]:
#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)
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]

3. Make a new list of NATO codes keeping only those that use the letter "a" in their *code*.

In [15]:
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)
['A', 'Alfa']
['B', 'Bravo']
['C', 'Charlie']
['D', 'Delta']
['I', 'India']
['L', 'Lima']
['O', 'Oscar']
['P', 'Papa']
['S', 'Sierra']
['T', 'Tango']
['X', 'X-ray']
['Y', 'Yankee']

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.
In [16]:
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)
[1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020]

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.

In [17]:
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?
282
[96, 44, 0, 58, 8, 76]
[96, 44, 0, 91, 93, 58, 67, 8, 76, 23, 3, 78, 34, 62, 61, 14, 18, 11, 1, 48, 96, 6, 54, 46, 60, 8, 57, 26, 55, 64, 48, 35, 24, 93, 45, 53, 1, 50, 0, 14, 47, 37, 5, 58, 16, 55, 14, 93, 77, 95]

More Data Types

Comprehensions

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

In [19]:
#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)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]

Pseudocode and Comments

Pseudocode

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

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

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

Comments

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.

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

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.

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

In [25]:
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))
50
0.1550322254103288