我对以下代码有两个问题。 一,第一次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
”每个缩进级别使用4个空格。“ - [PEP 8 - Python代码样式指南](http://www.python.org/dev/peps/pep-0008/#indentation)。如果你使用一致的缩进,你会发现更容易发现错误。 – Johnsyweb 2013-03-08 21:35:41
如果包含错误消息,它将帮助人们回答您的问题,因为语法错误可能在任何地方。 – askewchan 2013-03-08 21:38:56