货币转换器计划IF / Else声明

时间:2014-07-03 18:16:56

标签: python

我试图在Python上编写货币转换器程序,我的IF / Else语句似乎有问题。我写了#34;你想转换吗?"作为一个问题,如果答案开头于" 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 :(得分:1)

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

  
    
      

answer =输入("你想转换吗?")

    
  

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

答案 1 :(得分: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')

答案 2 :(得分:0)

将elif更改为:

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

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

答案 3 :(得分: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')