Home | Computer Science
A function that greets a person:
def greet(name):
return f"Hello, {name}! How are you?"
message = greet("John")
print(message) # Output: Hello, John! How are you?
OUTPUT
A function that checks if a number is even:
def is_even(number):
return number % 2 == 0
print(is_even(10)) # Output: True
print(is_even(7)) # Output: False
OUTPUT
A function that calculates the factorial of a number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)
OUTPUT
The letter "f" before the string is used to create an f-string (formatted string literal) in Python.
num1 = 5
num2 = 3
ans = num1 + num2
# Using f-string to format the string
print(f"The addition of {num1} and {num2} results {ans}.")
OUTPUT