More with Subroutine
Parameters
Let's put those subroutines to better use by sending them information using parameters and making them do different things based on different inputs.
If you change the ingredients in a recipe, you get a different kind of cake. Let's do that with subroutines.In a subroutine, the () are for the argument (FYI argument is another word for parameter). These are the pieces of information we pass to the code. These can be variable names that are made up for the first time within the argument ().
Here is a simple subroutine that uses the argument to take in the name of an ingredient and expresses its opinion (quite strongly) about the ingredient that the user typed. For example, 'chocolate' is amazing, but 'broccoli'...not so much.
def whichCake(ingredient):
if ingredient == "chocolate":
print("Mmm, chocolate cake is amazing")
elif ingredient == "broccoli":
print("You what mate?!")
else:
print("Yeah, that's great I suppose...")
Here in this above code , we have not called the subroutine yet.
We call it in the same way as before. However, instead of leaving the () blank, we send the code a message.
What happens when you add this to the end of your code above?
whichCake("chocolate")
We can have as many arguments as we want, separated by commas.
Now, this subroutine is expecting three arguments: ingredient, base, and coating:
def whichCake(ingredient, base, coating)
def whichCake(ingredient, base, coating):
if ingredient == "chocolate":
print("Mmm, chocolate cake is amazing")
elif ingredient == "broccoli":
print("You what mate?!")
else:
print("Yeah, that's great I suppose...")
print("So you want a", ingredient, "cake on a", base, "base with", coating, "on top?")
whichCake("carrot", "biscuit", "icing")
def whichCake(ingredient, base, coating):
if ingredient == "chocolate":
print("Mmm, chocolate cake is amazing")
elif ingredient == "broccoli":
print("You what mate?!")
else:
print("Yeah, that's great I suppose...")
print("So you want a", ingredient, "cake on a", base, "base with", coating, "on top?")
userIngredient = input("Name an ingredient: ")
userBase = input("Name a type of base: ")
userCoating = input("Fave cake topping: ")
whichCake(userIngredient, userBase, userCoating)
Coding Challenge :
Create subroutines that will roll a dice with any number of sides (essentially as big of a number as you like). Write one subroutine with one parameter that allows us to call a function (such as rollDice).Example:
Infinity Dice 🎲
How many sides?: 600
You rolled 532
Roll again? yes
You rolled 102
Roll again? no
def rolldice(sides):
import random
while True:
roll_again= input("Roll Again:")
if roll_again == "yes":
dice_output=random.randint(1,sides)
print("you rolled",dice_output)
continue
else :
break
call_a_dice=int(input("your dice has side of:"))
rolldice(call_a_dice)
Let's do this with the return command
The return command sends some information back to the part of the code that called it. This means the function call is replaced with whatever was returned.
We saw this before with importing libraries and random numbers. We could use the random number wherever we wanted.
def add_numbers(num1, num2):
sum = num1 + num2
return sum
print(result) # Output will be 8
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return average
# Example usage:
scores = [75, 80, 90, 85, 95]
avg_score = calculate_average(scores)
print("Average score:", avg_score)
Example for OTP generation
import random
pin = "" #this is the empty string
for i in range(number): #for loop shows defined amount of random numbers
pin += str(random.randint(0,9)) #we want a string of random numbers between 0-9
return pin
digits_of_pin= int(input("how manny digits",))
pinPicker(digits_of_pin)
myPin = pinPicker(digits_of_pin)
print(myPin)
Example for getting integers of set of any numbers as an input and average of the list of numbers :
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return average
# Taking inputs from the user
input_numbers = input("Enter numbers separated by spaces: ")
numbers_list = [int(num) for num in input_numbers.split()]
# Calculating average
avg_score = calculate_average(numbers_list)
# Printing the result
print("Average score:", avg_score)
# Taking inputs from the user
input_numbers = input("Enter numbers separated by spaces: ")
# Splitting the input string and converting to integers
numbers_list = [int(num) for num in input_numbers.split()]
# Filtering out even numbers using list comprehension
even_numbers = [num for num in numbers_list if num % 2 == 0]
# Printing the result
print("Even numbers:", even_numbers)
def calculate_rectangle_area(length, width):
area = length * width
return area
# Example usage:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_rectangle_area(length, width)
print("The area of the rectangle is:", area)
Example- Take a list of numbers as input and returns the maximum value in the list. Here's how we can implement it:
def find_maximum(numbers):
if not numbers:
return None # Return None if the list is empty
max_value = numbers[0] # Initialize max_value with the first element
for num in numbers:
if num > max_value:
max_value = num
return max_value
# Example usage:
input_numbers = input("Enter numbers separated by spaces: ")
numbers_list = [int(num) for num in input_numbers.split()]
max_value = find_maximum(numbers_list)
if max_value is not None:
print("The maximum value is:", max_value)
else:
print("The list is empty.")
Explanation:
def find_maximum(numbers):: This line defines a function named find_maximum that takes a list of numbers (numbers) as input. Inside the function, it iterates through the list to find the maximum value.
if not numbers:: This line checks if the list is empty. If it is, the function returns None because there is no maximum value to find in an empty list.
max_value = numbers[0]: This line initializes the variable max_value with the first element of the list, assuming it as the maximum value initially.
The for loop iterates over each number in the list. If a number is greater than the current maximum value (max_value), it updates max_value to that number.
return max_value: This line returns the maximum value found in the list back to the caller.
input_numbers = input("Enter numbers separated by spaces: "): This line prompts the user to enter numbers separated by spaces and reads the input as a string.
numbers_list = [int(num) for num in input_numbers.split()]: This line splits the input string into substrings based on whitespace, converts each substring to an integer using int(), and creates a list of these integers (numbers_list).
max_value = find_maximum(numbers_list): This line calls the find_maximum function with the provided list of numbers. It stores the returned maximum value in the variable max_value.
The final if statement checks if the max_value is not None (i.e., the list is not empty). If it's not None, it prints out the maximum value. Otherwise, it prints that the list is empty.
Example-takes a string as input and returns the count of vowels (a, e, i, o, u) in the string. Here's how we can implement it:
def count_vowels(input_string):
vowels = "aeiou"
count = 0
for char in input_string:
if char.lower() in vowels:
count += 1
return count
# Example usage:
input_string = input("Enter a string: ")
vowel_count = count_vowels(input_string)
print("Number of vowels:", vowel_count)
No comments:
Post a Comment