货币兑换程序

2024-03-28 11:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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')

Tags: to答案answer程序youconvertinputif
3条回答

将elif改为:

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

由于字符串已更改为小写,"Y"比较将永远不匹配。在

首先,您的问题会导致一个错误,因为您要求用户输入一个字符串,然后试图将其转换为一个float,但这不起作用。第1行应该是

answer = input("Do you want to convert?")

接下来,可能只是问题中的格式错误,但是if语句不起作用,因为需要缩进语句中的行。在

使用无限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')

相关问题 更多 >