如何在 if 语句中嵌套 while 循环? (Python)

问题描述 投票:0回答:2

我对于 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.')

我并没有真正尝试任何东西,但是编译器/解释器(我永远会把它们搞混🙃)返回了一个语法错误。

python if-statement while-loop nested
2个回答
0
投票
Python 中的块是通过缩进定义的,因此如果您希望在

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.')
    

0
投票
缩进是关键。

... if is_authorized(user): while keepGoing == 'y': ... keepGoing = input('Do you ... ')
    
© www.soinside.com 2019 - 2024. All rights reserved.