以下代码有两个问题。 第一,第一个raw_输入如果我试图以与'run again'的原始输入生命周期相同的方式格式化它,我会得到一个语法错误,我不知道为什么。在
第二,一旦我运行完程序并点击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
我看到了一些问题:
while total15 <= 0:
之类的语句?似乎您需要使用if
语句。。在total15
或total20
,因此,如果用户重新运行您的程序,它将不会计算和输出小费金额(因为这些变量具有非零值)。在代码功能的问题在while循环中:
您不需要这个,并且在第一次迭代之后无法得到答案的原因是您已经将
total15
设置为大于0
的数字。如果删除这个while循环并将循环中的所有内容向左移动,则代码将正常工作。在要回答格式化问题,如果您只需将第一个
raw_input
调用中的字符串替换为'{:>50}'.format('Enter the total of your bill:')
,它应该可以工作。在此外,您可以通过一些工作来减少此代码的长度和复杂性。在
相关问题 更多 >
编程相关推荐