您好我正在学习python,我正在尝试制作一个将钱转换成美元,欧元或英镑的小程序。有人可以帮助我,告诉我为什么不工作? 感谢!!!
def calculate():
currency_input = input("Insert value:")
dollar = 34
euro = 36
pound = 52
select_currency = input("Insert currency(dollar,euro or pound):")
if select_currency is "dollar":
currency_input * dollar
elif select_currency is "euro":
currency_input * euro
elif select_currency is "pound":
currency_input * pound
else:
print ("Please select a currency(dollar,euro,pound)!")
calculate()
calculate()
答案 0 :(得分:0)
您正在测试身份,而不是平等。请改用==
:
if select_currency == "dollar":
is
测试名称select_currency
是否指的是同一个对象;两个对象可以是不同的但仍然具有相同的值,您可以使用==
来测试它。
您需要修复所有字符串测试,并实际存储计算结果:
if select_currency == "dollar":
result = currency_input * dollar
elif select_currency == "euro":
result = currency_input * euro
elif select_currency == "pound":
result = currency_input * pound
更容易在这里使用字典:
currencies = {
'dollar': 34,
'euro': 36,
'pound': 52,
}
if select_currency in currencies:
result = currency_input * currencies[select_currency]
else:
print ("Please select a currency(dollar,euro,pound)!")
答案 1 :(得分:0)
您应该使用==
而不是is
,因为在这种情况下,is
将无法执行您认为的操作。更多关于here。
使用.lower()
允许用户也输入Dollars
并仍然成功。
您似乎希望能够在用户输入无效信息时进行处理。您应该使用try
except
块来确保用户只输入currency_input
使用while True
循环继续询问用户输入是否正确。如果他们输入了正确的输入,我们就会停止询问break
语句。
字典可以轻松存储货币名称及其相关值。
对于所有货币,数学运算也是相同的,唯一改变的是货币的价值(美元,欧元......),所以我们可以查看用户选择的内容,然后乘以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())
感谢Martijn Pieters指出了两项改进。