def say_hello():
print("Hello, friend!")
# Using the function
say_hello()Explanation:
- We define a function called
say_hellousing thedefkeyword. - The function doesn't take any parameters (that's why the parentheses are empty).
- Inside the function, we have one line of code that prints a message.
- To use (or "call") the function, we write its name followed by parentheses.
def greet(name):
print(f"Hello, {name}!")
# Using the function
greet("Alice")
greet("Bob")Explanation:
- This function,
greet, takes one parameter calledname. - When we call the function, we provide a value for
nameinside the parentheses. - The function uses this
nameto create a personalized greeting. - We can call the function multiple times with different names.
def add_five(number):
result = number + 5
return result
# Using the function
answer = add_five(10)
print(answer) # This will print 15Explanation:
- This function
add_fivetakes a number as input. - It adds 5 to this number and stores it in
result. - The
returnstatement sends this result back to wherever the function was called. - When we use the function, we can store its returned value in a variable (like
answer).
def calculate_rectangle_area(length, width):
area = length * width
return area
# Using the function
rectangle1_area = calculate_rectangle_area(5, 3)
print(f"The area of the rectangle is: {rectangle1_area}")Explanation:
- This function takes two parameters:
lengthandwidth. - It multiplies these values to calculate the area of a rectangle.
- The calculated area is then returned.
- When calling the function, we need to provide two values, one for each parameter.
def greet_with_title(name, title="Mr."):
print(f"Hello, {title} {name}!")
# Using the function
greet_with_title("Smith")
greet_with_title("Johnson", "Dr.")Explanation:
- This function has two parameters:
nameandtitle. titlehas a default value of "Mr.". This means if we don't provide a title, it will use "Mr.".- In the first function call, we only provide the name, so it uses the default title.
- In the second call, we provide both a name and a title, overriding the default.
def get_name_parts(full_name):
parts = full_name.split()
first_name = parts[0]
last_name = parts[-1]
return first_name, last_name
# Using the function
first, last = get_name_parts("John Doe Smith")
print(f"First name: {first}")
print(f"Last name: {last}")Explanation:
- This function takes a full name as input.
- It uses the
split()method to separate the name into parts. - It then assigns the first part to
first_nameand the last part tolast_name. - The function returns both of these values.
- When calling the function, we can assign both returned values to separate variables at once.
def find_longest_word(word_list):
longest_word = ""
for word in word_list:
if len(word) > len(longest_word):
longest_word = word
return longest_word
# Using the function
words = ["apple", "banana", "cherry", "date", "elderberry"]
longest = find_longest_word(words)
print(f"The longest word is: {longest}")Explanation:
- This function takes a list of words as input.
- It uses a for loop to go through each word in the list.
- It compares the length of each word with the current longest word.
- If a longer word is found, it becomes the new longest word.
- After checking all words, the function returns the longest one found.
def classify_temperature(temp):
if temp < 0:
return "Freezing"
elif temp < 10:
return "Cold"
elif temp < 20:
return "Cool"
elif temp < 30:
return "Warm"
else:
return "Hot"
# Using the function
temperature = 25
classification = classify_temperature(temperature)
print(f"{temperature} degrees is classified as: {classification}")Explanation:
- This function takes a temperature value as input.
- It uses a series of if-elif-else statements to classify the temperature.
- Each condition checks if the temperature is below a certain threshold.
- The function returns the appropriate classification as a string.
- When we call the function, it evaluates the input and returns the classification.
def sum_even_numbers(numbers):
total = 0
for num in numbers:
if num % 2 == 0: # Check if the number is even
total += num
return total
# Using the function
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sum = sum_even_numbers(number_list)
print(f"The sum of even numbers is: {even_sum}")Explanation:
- This function takes a list of numbers as input.
- It initializes a
totalvariable to keep track of the sum. - It loops through each number in the list.
- For each number, it checks if it's even by using the modulo operator (%).
- If the number is even, it's added to the total.
- After checking all numbers, the function returns the total sum of even numbers.
Create a function called calculate_grade that takes a student's score as a parameter. The function should return "A" for scores 90 and above, "B" for scores 80-89, "C" for 70-79, "D" for 60-69, and "F" for anything below 60.
Create a function called count_vowels that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels.
-
Write a function called
calculate_averagethat takes a list of numbers as input and returns the average of those numbers. -
Create a function
is_palindromethat takes a string as input and returns True if it's a palindrome (reads the same forwards and backwards), and False otherwise. Ignore spaces and capitalization. -
Write a function
fibonaccithat takes a number n as input and returns the nth number in the Fibonacci sequence. -
Create a function
prime_factorsthat takes a number as input and returns a list of its prime factors. -
Write a function
reverse_wordsthat takes a sentence as input and returns the sentence with each word reversed, but the order of words in the sentence remains the same. -
Create a function
caesar_cipherthat takes a string and a shift value as input, and returns the string encoded using the Caesar cipher technique. -
Write a function
binary_to_decimalthat converts a binary number (given as a string) to its decimal equivalent. -
Create a function
find_common_elementsthat takes two lists as input and returns a list of elements that are common to both input lists. -
Write a function
is_anagramthat takes two strings as input and returns True if they are anagrams (contain the same letters in different orders), and False otherwise. -
Create a function
generate_passwordthat takes a length as input and generates a random password of that length, including uppercase and lowercase letters, numbers, and special characters. -
Write a function
flatten_listthat takes a nested list as input and returns a flattened version of the list. -
Create a function
word_frequencythat takes a string as input and returns a dictionary with words as keys and their frequencies as values. -
Write a function
remove_duplicatesthat takes a list as input and returns a new list with duplicates removed, preserving the original order. -
Create a function
matrix_transposethat takes a 2D list (matrix) as input and returns its transpose. -
Write a function
validate_emailthat takes a string as input and returns True if it's a valid email address, and False otherwise.