我对于 Python 仍然是真的新手。就像,我只处于新手的第 4 章级别(之前的经验很少)。毫无疑问,我问这个问题有些操之过急,但我对自己的编程能力没有信心,这只是一种好奇。
我想知道如何将 while 循环放入 if 语句中。文本的示例是佣金计算器,我想知道如何循环程序,直到条件需要重新启动或结束。
这是示例代码(我添加的内容作为注释):
keepGoing = 'y'
while keepGoing == 'y':
sales = float(input('Enter the amount of sales: '))
commRate = float(input('Enter the commission rate: '))
commission = sales * commRate
print(f'The commission is ${commission:,.2f}.')
keepGoing = input('Do you want to calculate another commission (Enter y for yes): ')
#(Enter y for yes, or n for no)
#if keepGoing = 'y':
# (I didn't put anything here because this is where I got stuck)
#else:
# print('Thank you for using the commission calculator.')
我并没有真正尝试任何东西,但是编译器/解释器(我永远会把它们搞混🙃)返回了一个语法错误。
while
循环内发生某些事情,则需要比
while
更深一级缩进:
keepGoing = 'y'
while keepGoing == 'y':
keepGoing = input('Do you want to calculate another commission (Enter y for yes): ')
#(Enter y for yes, or n for no)
if keepGoing = 'y':
print('Okay, here we go again!')
else:
print('Thank you for using the commission calculator.')
...
if is_authorized(user):
while keepGoing == 'y':
...
keepGoing = input('Do you ... ')