2013-03-08 92 views
0

我对以下代码有两个问题。 一,第一次raw_input,如果我尝试格式化为raw_input生活再次运行的方式,我会得到一个语法错误,我不明白为什么。Python代码错误

第二,一旦我完成了运行程序并启动y,它会在停止时开始,但是如果我再次输入一个数字,它会回到问我是否想再次运行,就好像它做了什么本应该这样做。如果我输入负数或字母它会给我正确的错误信息,但如果我输入一个数字,它将无法正常工作。它只会跳到询问我是否想再次运行。

这发生在我添加了格式化代码后,在那之前我使用了空格,并且所有工作都正常。

total15 = 0 
total20 = 0 
while True: 
     print '' 
     while True: 
       try: 
        userNum = float(raw_input('       Enter the total of your bill:')) 
        if (userNum) > 0 and (userNum) != 0: 
         break 
        else: 
         print '' 
         print('{:^80}'.format('Oops! That was no valid number. Try again...')) 
         print '' 

       except ValueError: 
       print '' 
       print('{:^80}'.format("Oops! That was no valid number. Try again...")) 
       print '' 
     while total15 <= 0: 
      total15 = float((15*userNum)/100) 
      total20 = float((20*userNum)/100) 
      print '' 
      print('{:^80}'.format('You should leave ' + str(total15) + '$' + ' of tip' \ 
        ' for 15%' + ' or ' + str(total20) + '$' + ' for 20%')) 
      print '' 
     while True: 
      answer = raw_input(('{:>50}'.format('Run again? (y/n): '))) 
      if answer in ('y', 'n'): 
       print'' 
       break 
      print('{:>50}'.format('Invalid input.')) 
     if answer == 'y': 
      continue 
     else: 
      print '' 
      print('{:>45}'.format('Goodbye!')) 
      break 
+2

”每个缩进级别使用4个空格。“ - [PEP 8 - Python代码样式指南](http://www.python.org/dev/peps/pep-0008/#indentation)。如果你使用一致的缩进,你会发现更容易发现错误。 – Johnsyweb 2013-03-08 21:35:41

+2

如果包含错误消息,它将帮助人们回答您的问题,因为语法错误可能在任何地方。 – askewchan 2013-03-08 21:38:56

回答

2

与您的代码的功能,问题是在while循环:

while total15 <= 0: 

你不需要这一点,你不能得到答案的原因后第一次迭代是因为你已将total15设置为大于0的数字。如果你在while循环中删除这个循环,并把循环中的所有内容都移到左边,那么你的代码就可以工作

要回答你的格式问题,如果你只是把第一个raw_input调用中的字符串替换成'{:>50}'.format('Enter the total of your bill:'),它应该可以工作。

此外,您可以通过一些工作减少此代码的长度和复杂性。

2

我看到几个问题:

  1. 你为什么要使用之类的语句while total15 <= 0:?您似乎需要使用if语句代替。
  2. 您不会重置total15total20,因此如果用户重新运行程序,它将不会计算并输出提示的金额(因为这些变量具有非零值)。 “