这是我的代码:
import sys
import click
def Seats():
global seats
seats = 168
print("\nThe current seating capacity is {}\n".format(seats))
def Restart():
while True:
restart = click.confirm('\nWould you like to subtract 1 from seats?',
default=True)
if restart == True:
x = seats - 1
Seats()
elif restart == False:
print("\nOk, see you next time!\n")
sys.exit()
Seats()
Restart()
我想问用户“你想从座位上减1吗?” 然后从座位变量中减去一个,然后重复直到用户输入no
。
正如评论中所指出的,您的代码中的主要问题在这里:
def Seats():
global seats
seats = 168
print("\nThe current seating capacity is {}\n".format(seats))
无论何时何地您Seats
在代码中调用该函数,seats
都会重新定义的值,因为它seats = 168
会被执行。
指出问题后,我尝试编辑您的代码以保持相同的结构,以尝试向您展示如何解决问题,但我改变了主意。该代码尽管很小,但具有不必要的复杂逻辑和远非干净的语法。您是初学者,所以没有问题!正因为如此,我认为向您展示实现该算法的另一种方法会更有价值。它是这样的:
import click
seats = 168
while seats > 0:
subtract_seat = click.confirm('\nWould you like to subtract 1 from seats?', default = True)
if subtract_seat:
seats -= 1
print("\nThe current seating capacity is {}\n".format(seats))
else:
break
print("\nOk, see you next time!\n")
sys
库。你没有使用它while seats > 0
避免在没有更多座位时减去座位,也是用于与用户交互的主循环else
如果不满足第一个条件,该子句将自动处理#AshidoBestGirl
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句