Add some examples to functions

This commit is contained in:
2026-08-25 16:13:06 +02:00
parent 4df0cd11d2
commit caeb8808be
2 changed files with 49 additions and 5 deletions

View File

@@ -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})")

View File

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