Exercises
Contents
4.2. Exercises#
4.2.1. Exercise 1#
In this exercise we want to determine if a number is positive (>0) or not. Write a function that will return a value based on whether the number is positive or not. Then try it out with different arguments.
# write the function here
# write the function calls here
4.2.2. Exercise 2#
Write a function that will receive an arbitrary number of integer arguments and will compute their average. Test it with different numbers of arguments.
# write the function here
# write the function calls here
4.2.3. Exercise 3#
Suppose that we have the following piece of code:
def find_square(x):
return x**2
print(find_square(2))
Do you think it will run? Explain your reasoning.
# write your answer as a comment here
4.2.4. Exercise 4#
Suppose that we have the following piece of code:
def function_xyz(x,y,z):
x = 5
if(y>0):
a = x*3
else:
b = z*2
return a*b
print(function_xyz(1,2,3))
print(function_xyz(1,-2,3))
print(function_xyz(1,0,3))
Do you think any of the function calls will execute correctly? Explain your reasoning.
# write your answer as a comment here
4.2.5. Exercise 5#
Suppose that we have the following piece of code:
def function_xyz(x,y,z):
x = 5
if(y>0):
a = x*3
if(z>0):
b = z*2
return a*b
print(function_xyz(1,2,3))
print(function_xyz(1,-2,-3))
Do you think any of the function calls will execute correctly? Explain your reasoning.
# write your answer as a comment here
4.2.6. Exercise 6#
Remember the Christmas tree we were trying to build on exercise 6 of chapter 3? Now we want to be more flexible and based on our available space build different-sized Christmas trees, not only with 5 stars. Modify the following code so that it takes different numbers, and using them builds Christmas trees of different sizes. (You need to substitute only the question marks.)
def build_christmas_tree( ? ):
for i in range(0, ? ):
for j in range(0,(i+ ?)):
if j>=(?-(i+1)):
if (j%2==0 and i%2==0) or (j%2==1 and i%2==1):
print('*', end='')
else:
print(' ', end='')
else:
print(' ', end='')
print(' ')
Cell In[8], line 1
def build_christmas_tree( ? ):
^
SyntaxError: invalid syntax
# define a variable for the length
# call the function