JamCoders

💾 Download

Lecture 3, Part 1 Exercises

In [ ]:
# Always run this code.
%config InteractiveShell.ast_node_interactivity="none"

Question 0: Recap

Answer the following questions

0.1

  1. What is a short way to write: for i in [0, 1, 2, 3, 4, 5, 6, 7] using the range() function?
  2. Consider the following two functions:
def my_function(x):
     return x

def my_function2(y):
     return y

Explain why these functions will do the exact same thing despite having different parameter names. 3. Consider the following code:

for a in [0, 1, 2]: # loop 1
  for b in [0, 1, 2]: # loop 2
    print('hi')
  print('bye')

When a = 0, how many times is 'hi' printed?

How many times is 'bye' printed? When a = 1, how many times is 'hi' printed? How many times is 'bye' printed? 4. Consider the same code as question 3. Overall, how many times is the inner loop (commented #loop 2) run? How many times is the outer loop (commented #loop 1) run? 5. Consider the following code:

for a in [0, 1, 2]: # loop 1
  print(' ') # Print a space
print('!') # Print a !

for a in [0, 1, 2]: # loop 2
  print('!')
print(' ')

Explain why the first loop (#loop 1) will print only one ! mark. Why does (#loop 2) print three ! marks?

  1. Consider the following code:
def square(x):
  x = 5
  return x * x

print(square(5))
print(square(7))

We would like square(7) to return 7 x 7 = 49. What does it actually return?

  1. Consider the same code as question 6. Even though the code is wrong, why the function give the correct output if you call square(5), (or square(-5))? Can you change the code to be correct on all inputs?

  2. Consider the following code:

def function_that_returns_five():
  return 5

def function_that_prints_five():
  print(5)

What should be printed to the console when I run the following: (Note: the console shows the printed output from code when we run it) 9. If I run the line: print(function_that_prints_five()), I get:

  • function_that_returns_five()
  • function_that_prints_five()
  • print(function_that_returns_five()
output:
>>> 5
>>> None

Why is 5 printed out? Why is None printed out?

In [ ]:
# Questions 1, 2, 3, 4, 5, 6 here
In [ ]:
# Question 7 here
def square(x):
  pass
In [ ]:
# Question 8, 9 here
In [ ]:

Question 1

1.1

Print the integers from 0 - 10 using a for loop

In [ ]:

1.2

Print the integers from 0 - 10 using a while loop

In [ ]:

1.3

Write a function that takes x as input and prints it

In [ ]:

1.4

Write a function that takes x and prints every number between 0 and x-1 using a for loop

In [ ]:
def printValues(x):
    # Code here!
    pass

printValues(5)

1.5

Write a function that takes x and prints every number between 0 and x-1 using a while loop

In [ ]:
def printValues(x):
    # Code here!
    pass
    
printValues(5)

Great job!

This is tricky material, as always, if it's confusing or frustrating that's good. Always feel free to ask a TA for help and discuss with other students.

Question 2

2.1

Use code to verify that the number 4 is even. Hint: you could make use of math operators like %.

In [ ]:

2.2

Write a function that takes x and returns True if x is even

In [ ]:
def isEven(x):
    # Code here!
    pass

print(isEven(4))

2.3

Write a function that takes x and prints every number between 0 and x-1 using a for loop

In [ ]:
def printValues(x):
    # Code here!
    pass
    
printValues(6)

2.4

Write a function that takes x and prints every EVEN number between 0 and x-1 using a for loop

In [ ]:
def printEvenNumbers(x):
    # Code here!
    pass
    
printEvenNumbers(9)
0
2
4
6
8

2.5

Write a function that takes x and prints every EVEN number between 0 and x-1 using a while loop

In [ ]:
def printEvenNumbers(x):
    # Code here!
    pass
            
printEvenNumbers(9)

2.6

Using while True:, print the integers from 0 - 10

In [ ]:

2.7

Write a function that takes x and prints every EVEN number between 0 and x-1 using while True:

In [ ]:
def printEvenNumbers(x):
    # Code here!
    pass
        
num = int(input('Enter a number? '))
printEvenNumbers(num)

2.8

Write a function that takes x and prints every EVEN number between 0 and x-1 using a for loop, without control flow (i.e. no if statements)

In [ ]:
def printEvenNumbers(x):
    # Code here!
    pass
        
printEvenNumbers(10)

Question 3

3.1

Create a list called my_list with 3 integers

In [ ]:

3.2

Print the first element in my_list

In [ ]:

3.3

Print the length of my_list

In [ ]:

3.4

Print every number in my_list using a for loop.

In [ ]:

3.5

Write a function that takes a list and prints all items in it using a for loop

In [ ]:
def printListElem(L):
   # Code here!
   pass
        
printListElem([2,3,'Key', 'one', 2.5])

3.6

Print the sum of all the elements in my_list using a for x in y loop

In [ ]:
my_list = [2,4,7,8]
# Code here!

3.7

Write a function that takes a list and prints the sum of all items in it using a for x in y loop

In [ ]:
my_list = [2,4,7,8]

def printSum(L):
    # Code here!
    pass

printSum(my_list)

3.8

Write a function that takes a list and prints the sum of all items in it using a while loop

In [ ]:
# Create my list
my_list = [2,4,7,8]

def printSum(L):
    # Code here!
    pass
    
printSum(my_list)

3.9

Write a function that takes a list and prints the sum of all items in it that uses for x in range() loop, and not a while loop.

In [ ]:
my_list = [2,4,7,8]

def printSum(L):
   # Code here!
   pass
   
printSum(my_list)

Question 4

4.1

Create a string called my_string with the value "racecar"

In [ ]:
my_string = 'racecar'

4.2

Print the first character of my_string

In [ ]:

4.3

Print the last character of my_string by making use of the len function

In [ ]:

4.4

Print True if the first and last characters of my_string are the same

In [ ]:

4.5

Write a function that takes a string and returns True if the first and last characters of the string are the same and False otherwise

In [ ]:
def checkChar(str1):
    # Code here!
    pass

checkChar('rar')

4.6

Write a function that takes a string and returns True if the second and second to last characters of the string are the same and False otherwise

In [ ]:
def checkSecond(str1):
    # Code here!
    pass
    
checkSecond('racecar')

Note: A palindrome is a word that is spelt the same forward as it is backwards.

  • Palindromes:
    • racecar
    • madam
    • 12321

4.7

For each of the following strings, say whether they are palindromes (in words):

  1. kayak
  2. 12323
  3. hello
  4. noon

Fill this in.

4.8

Write a function that takes a string and returns True if the string is a palindrome and False otherwise

In [ ]:
def isPalindrome(str1):
    # Code here!
    pass

print(isPalindrome('noon'))
print(isPalindrome('Hello'))
print(isPalindrome('kayak'))
print(isPalindrome('123123'))

Challenge: Would you be able to solve the above problem in a different way?

(One way is to generate the reversed string, then check equality. Another way is to check index by index, without creating a copy of the string! There could be even more ways!)

In [ ]:
def isPalindrome(string):
    # Code here!
    pass

isPalindrome('aza')

Question 5

5.1

Run the code below to print the numbers from 0 - 20

In [ ]:

5.2

Add to the code in the block above (without deleting anything) to break out of the loop after printing the numbers 0 - 5

In [ ]:

5.3

Now, use the code from 5.1 to print all the numbers between 0 and 20 that are not multiples of 3.

In [ ]:
for i in range(21):
    if i % 3 != 0:
        print(i)

5.4

Write code that will print all the numbers between 0 and 20 that are not multiples of 3 using continue

In [ ]:

5.5

Try running the code below and see what happens (hint: you might need to use the stop button at the top of the page).

In [ ]:
i = 0
while True:
    i += 1
    print(i)

5.6

Now, add lines to the code above to only print the numbers up to 20.

In [ ]:

5.7

Now, using continue, use the same code from 5.6 to print the numbers up to 20 that are not multiples of 3.

In [ ]:

Question 6

6.1

Write a program to sum numbers from 1 to 20 using a while True: loop and break

In [ ]:

6.2

Write a program that adds all the integers from 1 to 20 except 10 and 11.

In [ ]:

Question 7 Challenge

Write a program that displays the first fifty prime numbers.

In [ ]:

Question 8

8.1

What is the output of the following code?

i = 0
def func(x):
    i = 10
    print(i, x)
    
func(5)
In [ ]:

What is the value of i after the above code is executed?

In [ ]:

8.2

What is the output of the following code?

i = 8
def func2():
    i += 10
    print(i)
    
func2()
In [ ]:

What is the value of i after the above code is executed?

In [ ]:

8.3

What will j be when printed in the code below?

def func1(x):
    j = 10
    print(j, x)
    
def func2(x):
    j = 5
    func1(x)
    print(x)
    
func2(3)
print(j)
In [ ]:
# Explain why in this comment!

8.4

Now, we are going to create a FortuneTeller function that will print out a fortune depending on the value of the input given. Use the code comments below to help you complete this task.

In [ ]:
# Make a variable `inputval` with the value 1.


# Function header that creates a function called `FortuneTeller` that takes no arguments.
def FortuneTeller():

    # Add a local variable to `FortuneTeller` called `inputval` that has the value 3.
    
    # Add a conditional that checks when inputval is equal to 1. Print out "You will be lucky" if inputval equals 1.

    # Add a conditional that checks when inputval is equal to 2. Print out "You will be unlucky" if inputval equals 2.
    
    # Add a conditional that checks when inputval is equal to 3. Print out "You will get money" if inputval equals 3.
    
    # Add a conditional that checks when inputval is equal to 4. Print out "You will lose money" if inputval equals 4.
    
    # Add a conditional that checks when inputval is equal to 5. Print out your own statement if inputval equals 5.
    
# Call the FortuneTeller function and observe the output value

8.5

What value did you get when you ran the code above? Did the if statement for inputval==1 or inputval==3 occur? Was it the value you expected?

In [ ]:
# Comment here!

8.6

How can you change the code in 6.4 so that the output given is "You will lose money"?

In [ ]:
# Comment here

8.7

In the code block below, what will be the output? Was it what you expected?

i = 100
for i in range(3):
    print(i)
In [ ]:
# Comment here

8.8

Will (a) and (b) output the same thing? If not, explain why.

(a)

k = 0
for i in range(3):
    print(k)

(b)

k = 0
for i in range(3):
    k = 6
    print(k)
In [ ]:
# Comment here

8.9 -optional

Elijah wrote the code in 8.4, but Natnael says that that code is "bad practice" (meaning it is inefficient, confusing to read, or not proper convention), and it is better to modify 8.4 to be a function that takes the inputval as a parameter.

Follow Natnael's advice, and explain why he might be right!

In [ ]:
# Make the edits here!
def FortuneTeller():
    pass
In [ ]:
# Comment on why it doesn't make sense to define an inputval locally inside the function
# and why having inputval be a function parameter may be better than having inputval be a global variable