Add some examples to functions
This commit is contained in:
@@ -3,3 +3,29 @@ def hello(name):
|
|||||||
|
|
||||||
username = input('What is your name stranger?\n>')
|
username = input('What is your name stranger?\n>')
|
||||||
hello(username)
|
hello(username)
|
||||||
|
|
||||||
|
# Another example using functions and return code:
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
# Defining the function:
|
||||||
|
def get_answer(answer):
|
||||||
|
if answer <10:
|
||||||
|
return "The answer is smaller than 10"
|
||||||
|
elif answer == 10:
|
||||||
|
return "The answer is 10."
|
||||||
|
else:
|
||||||
|
return 'The answer is greater than 10'
|
||||||
|
|
||||||
|
# Generating a random number, using that random number to define a variable by using it as an argument in the funtion,
|
||||||
|
# and printing the result:
|
||||||
|
random_number = random.randint(1, 20)
|
||||||
|
result = get_answer(random_number)
|
||||||
|
print(result)
|
||||||
|
|
||||||
|
# The 3 lines above can be rewritten to a single line:
|
||||||
|
print(get_answer(random.randint(1, 20)))
|
||||||
|
|
||||||
|
# And the check to see if the code is working as it should:
|
||||||
|
print(f"(It is {random_number})")
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,25 @@
|
|||||||
def hello(name):
|
# Again
|
||||||
print(f'Hello {name}! How are you?')
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
def get_answer(answer):
|
||||||
|
if answer <10:
|
||||||
|
return "The answer is smaller than 10"
|
||||||
|
elif answer == 10:
|
||||||
|
return "The answer is 10."
|
||||||
|
else:
|
||||||
|
return 'The answer is greater than 10'
|
||||||
|
|
||||||
|
random_number = random.randint(1, 20)
|
||||||
|
|
||||||
|
result = get_answer(random_number)
|
||||||
|
|
||||||
|
|
||||||
|
print(get_answer(random.randint(1, 20)))
|
||||||
|
|
||||||
|
print(result)
|
||||||
|
print(f"(It is {random_number})")
|
||||||
|
|
||||||
|
|
||||||
username = input('What is your name stranger?\n>')
|
|
||||||
hello(username)
|
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user