Python 货币转换器程序IF/Else语句
我试图在Python上编写一个货币转换器程序,但我的IF/Else语句似乎有问题。我写了“你想转换吗?”作为一个问题,如果答案以“y”开头,那么用户将开始程序。如果答案为“n”,则程序将退出。但现在我试着写一个声明,如果任何其他字母写的不是“y”或“n”,那么就会出现一条消息,说答案无效。目前看来是这样的:Python 货币转换器程序IF/Else语句,python,Python,我试图在Python上编写一个货币转换器程序,但我的IF/Else语句似乎有问题。我写了“你想转换吗?”作为一个问题,如果答案以“y”开头,那么用户将开始程序。如果答案为“n”,则程序将退出。但现在我试着写一个声明,如果任何其他字母写的不是“y”或“n”,那么就会出现一条消息,说答案无效。目前看来是这样的: answer=float(input('Do you want to convert?')) if answer.lower().startswith("n"): print("Go
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')
使用无限while循环:
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')
将elif更改为:
elif answer.lower().startswith("y"):
由于字符串已更改为小写,因此比较将永远不匹配。为什么将输入的答案转换为浮点,然后将其视为字符串? 试试这个:
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行应该是 回答=输入(“您想转换吗?”)
接下来,这可能只是您的问题中的格式错误,但您的if语句不起作用,因为您需要缩进语句中的行。请回答您的问题并修复缩进。谢谢您的回答!