you should use ==
instead of is
because is
will not do what you think it does in this case. More on that here.
Use .lower()
to allow the user to also enter Dollars
and still succeed.
It seems that you want to be able to handle when the user inputs invalid information. You should use a try
except
block to make sure the user enter only numbers for the currency_input
Use while True
loops to keep on asking the user for correct input. If they enter correct input we stop asking with the break
statement.
Dictionaries make it easy to store the currency name and their associated value.
Also the math is pretty the same for all currencies, the only thing that changes is the value of the currency (dollars, euro, ...) so we can just look up what the user chose and than multiply that times the currency_input
def calculate():
# we only want the user to input numbers
while True:
try:
currency_input = float(input('Insert value: ')) # input always returns a str, we need to type cast
break # if input is valid we break out of the loop and move on
except TypeError: # handle the error when the input is not a number
print('Please enter a number.')
# use a dictionary because it is easier to read
currency_dict = {
'dollar': 34,
'euro': 36,
'pound': 52}
# get the type of currency and do the math
while True:
select_currency = input('Insert currency(dollar,euro or pound): ').lower()
if select_currency not in currency_dict: # if the users enter something that is not in the dict
print('Invalid currency') # oops, try again
else:
money = currency_input * currency_dict[select_currency] # we do the math
return money # return allows us to further manipulate that variable if we so desire
print(calculate())
Thanks to Martijn Pieters for pointing out two improvements.