lecture_9_practice

html

School

University of California, Davis *

*We aren’t endorsed by this school

Course

1

Subject

Computer Science

Date

Feb 20, 2024

Type

html

Pages

2

Uploaded by DukeFly4004

Report
Practice: Functions Create a function called say_goodbye which displays the text "Goodbye!" In [1]: def say_goodbye(): print("Goodbye!") Write code that calls the function say_goodbye In [2]: say_goodbye() Goodbye! Redefine the function say_goodbye to take a parameter called name , and have it display "Goodbye name!" where "name" is replaced by whatever was in the name variable In [4]: def say_goodbye(name): print("Goodbye "+name+"!") Write code that calls the function say_goodbye but with your name as a parameter In [5]: say_goodbye("Allison") Goodbye Allison! Try out the code below which counts from 0 to 4 slowly: In [6]: import time # We need the time library for the following examples In [7]: for i in range(5): print(i) time.sleep(1) 0 1 2 3 4 We can put that for loop in a function like this: In [8]: def counter(): for i in range(5): print(i) time.sleep(1) And then we can call it: In [9]: counter() 0 1 2 3 4 Now redifine counter by 1. copying the code above which defines counter 2. make the counter take a parameter called max 3. Have the range call use the parameter max In [10]:
def counter(max): for i in range(max): print(i) time.sleep(1) Now try calling the new version of counter but passing it the argument 7 In [11]: counter(7) 0 1 2 3 4 5 6 Create a function called multiply which takes two arguments, multiplies them together ( * ), and then returns the multiplied value In [12]: def multiply(num_1, num_2): return num_1 * num_2 Call the mutliply function with two numbers and save the result in a variable. Then print out the variable to see that the multiplied number was saved. In [13]: new_num = multiply(3, 5) display(new_num) 15 In [ ]:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help