我希望每次有新买家时,买家编号都会更改
total = 200 # Assigns 200 tickets to variable total
sold = 0 # Assigns 0 tickets to variable sold
count = 0
while sold < total: # Runs while loop as long as tickets sold is less than total tickets
remaining = total - sold # Assigns total - sold to variable remaining
if sold == 0: # If tickets are equal to 0
print("Welcome to Movies4Us!") # Prints "Welcome to Movies4Us!" if condition above is satisfied
else:
print('You are buyer NO.', count + 1, "." "The number of remaining tickets is now", remaining, ".") # Prints user's number and remaining amount of tickets
name = input('What is your name?: ')
tickets = input("How many tickets would you like to purchase?: ") # Asks user to enter desired amount of tickets to purchase
try:
tickets = int(tickets) # Converts variable tickets to integer type
if tickets > remaining: # If user enters more tickets than remaining tickets available
print("Sorry, there aren't that many tickets available.") # Prints no more tickets available
else:
sold += tickets # Updates value of variable sold into tickets
print("You have purchased", tickets, "tickets, Enjoy the movie", name, '!') # Prints the amount of tickets the user purchased
except ValueError: # If user inputs anything except for an integer
print("Invalid input. Please enter a number.") # Prints invalid input and asks user to input again
continue # Ends current loop and runs the while loop again
print ("There are no more tickets available.") # If number of tickets reached 0, program ends
尝试添加count = 0
和count + 1
您已经初始化了一个计数器:count = 0
。您只需要在每次有效购票时在循环中增加它。
在else
块中添加count += 1
,其中在语句sold += tickets
下进行了有效的票务购买。这将在每次成功购买发生时增加计数器。
如果要更新count的值,最简单和最清晰的方法是在print语句之前的行更新它。或者,您可以在代码的其他部分更新sold
的值。
if sold == 0: # If tickets are equal to 0
print("Welcome to Movies4Us!") # Prints "Welcome to Movies4Us!" if condition above is satisfied
else:
count += 1
print(f"You are buyer NO.{count}.", end=" ") # Use string interpolation
print(f"The number of remaining tickets is now {remaining}.") # Prints user's number and remaining amount of tickets
我还更新了这个,使用f-string进行格式化,否则你会遇到count值和后面的"."之间有额外空格的问题。
如果你真的不希望count+=1
有单独的行,可以在print语句中更新count inline,但前提是你不使用f-string,如果你使用:=
操作符,因为print语句的参数必须是表达式,所以正常的赋值会导致语法错误:
print('You are buyer NO.', count := count +1, ". The number of remaining tickets is now", remaining, ".") # Prints user's number and remaining amount of tickets