货币转换器程序IF/Else语句

-1 投票
4 回答
1411 浏览
提问于 2025-04-18 12:02

我正在尝试用Python写一个货币转换器程序,但在IF/Else语句上遇到了一些问题。我写了一个问题“你想转换吗?”如果用户的回答以“y”开头,那么程序就会开始。如果回答是“n”,那么程序就会退出。现在我想写一个语句,如果用户输入的其他字母不是“y”或“n”,就会显示一个“无效答案”的提示。目前的代码看起来是这样的:

answer=float(input('Do you want to convert?'))
if answer.lower().startswith("n"):
    print("Goodbye "+name)
    exit()
elif answer.lower().startswith("y") or ("Y"):
    Amount=int(input("Enter amount to convert:")) 
    currency_1=input("Currency you want to convert from:")
    currency_2=input("Currency you want to convert to:")
else:
    print('Sorry. Invalid answer. Please start again')

4 个回答

0

使用一个无限循环:

while True:
   answer=str(input('Do you want to convert?'))
   if answer.lower()[0] == 'n':
       print("Goodbye "+name)
       exit()
   if answer.lower()[0] == 'y':
       break
   print('Invalid answer')
0

你为什么要把你的输入 answer 转换成浮点数,然后又把它当成字符串来处理呢?试试这个:

answer=str(input('Do you want to convert?'))
if answer.lower().startswith("n"):
    print("Goodbye "+name)
    exit()
elif answer.lower().startswith("y") or ("Y"):
    Amount=int(input("Enter amount to convert:")) 
    currency_1=str(input("Currency you want to convert from:"))
    currency_2=str(input("Currency you want to convert to:"))
else:
    print('Sorry. Invalid answer. Please start again')
1

首先,你的问题会导致错误,因为你让用户输入一个字符串,然后又试图把它转换成浮点数,这样是行不通的。第一行应该简单写成:

answer = input("你想转换吗?")

接下来,可能是你提问时格式有问题,但你的if语句没有正常工作,因为你需要把语句内部的行缩进。

0

把elif改成:

elif answer.lower().startswith("y"):

因为这个字符串已经变成小写了,所以"Y"的比较永远不会匹配成功。

撰写回答