Last active
January 24, 2022 19:01
-
-
Save hughlilly/8d68a7309dab2eceaa1d6c2d387b96e2 to your computer and use it in GitHub Desktop.
learn_python_extras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This time let's not use a string for the operation parameter. | |
# Since it's an either-or choice, a Boolean will do nicely. | |
# For an explanation of the use of the "*" in the definition block, see | |
# https://ivergara.github.io/boolean-arguments-to-functions-in-python.html | |
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int: | |
"""Calculates the sum (or difference) of two numbers. | |
Parameters: | |
`x` : int | |
The first number | |
`y` : int, optional | |
The second number (default is 1) | |
`subtraction`: bool, optional | |
Whether to perform subtraction. Default is False. | |
""" | |
if subtract: | |
return x - y | |
else: | |
return x + y | |
# Get two inputs from the user and cast them to integers | |
first = int(input("Enter a number: ")) | |
second = int(input("Enter another number: ")) | |
def ask_for_operation(): | |
user_choice = input("Do you want to subtract? (y/n): ") | |
# Convert to lowercase (for comparison later) | |
user_choice = user_choice.casefold() | |
return user_choice | |
# Ask if they want subtraction; False by default | |
subtract_chosen = False | |
user_choice = ask_for_operation() | |
first_letter = user_choice[0] | |
while first_letter != "n" or "y": | |
print("Sorry, your answer needs to start with a 'y' or an 'n'; please try again.") | |
user_choice = ask_for_operation() | |
if first_letter == "y": | |
subtract_chosen = True | |
operation = "minus" | |
elif first_letter == "n": | |
subtract_chosen = False | |
operation = "plus" | |
# Print the results of the two calculations | |
result = calculate(first, second, subtract=subtract_chosen) | |
print(f"{first} {operation} {second} is {result}") | |
# If you don't pass a second variable, the default value is used: | |
result = calculate(first, subtract=subtract_chosen) | |
print(f"{first} {operation} the default value is {result}.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment