循环行消失,while循环问题

时间:2019-03-01 03:58:07

标签: python if-statement while-loop

*我是python的新手,请保持柔和...

总体问题:我最近在编写的多个代码中遇到了一个问题,这些代码中的行被跳过,这显然对我来说是一个错误。我知道我一定在弄乱某些东西的顺序,但是我只是看不到它。我最近的问题可以在这里找到:Is there any reason Python would skip a line?

现在,我想编写一个用于预售有限数量票证的应用程序。条件如下:

“每个购买者最多可以购买4张票。总共有15张票可以预售。该程序应提示用户输入要购买的票数,然后显示张数。剩余的票。重复直到所有票都卖完,然后显示购买者总数。“

正在发生类似的问题。

buy = int()
ticket_num = 15
buyers = 0

while ticket_num > 0:
    buy = int(input("How many tickets would you like to purchase? "))
    if buy > 4:
        print("You cannot buy that many (4 max).")
        buy = input("How many tickets would you like to purchase? ")
    else:
        ticket_num = ticket_num - buy
        print("There are currently", ticket_num, "remaining.")
        buyers = buyers + 1

print() 

print("The total number of buyers was:", buyers)

“ else”结构中的打印行似乎没有被读取,我不太明白为什么...

任何人都可以使我对我的总体误解有什么了解吗??

2 个答案:

答案 0 :(得分:0)

我知道了。我有几个与此问题不正确的地方:

  • 我没有足够的条件语句(elif)不能满足要求
  • 我不需要在if语句中再次让buy变量收集输入,因为while循环已经使程序再次提示输入。
  • 我根本不需要在while循环之外使用buy变量,我只需要在'if'语句中使用它之前对其进行初始化。

解决方案如下:

tickets = 15
buyers = 0
print("There are currently", tickets, "tickets available.")

while tickets > 0 :
    buy = int(input("How many tickets would you like to purchase? "))
    if buy <= 4 and tickets - buy >= 0:
        tickets = tickets - buy
        buyers = buyers + 1
        print("There are", tickets, "tickets remaining.")
    elif buy > 4:
        print("You cannot buy that many (4 max).")
    elif tickets - buy < 0:
        print("You can only buy what remains. Please see previous 'remaining' message.")

print()
print("There was a total of", buyers, "buyers.")

答案 1 :(得分:0)

buy = int()
ticket_num = 15
buyers = 0

while ticket_num > 0:
    buy = int(input("How many tickets would you like to purchase? "))
    if buy > 4:
        print("You cannot buy that many (4 max).")
        #buy = input("How many tickets would you like to purchase? ")
    else:
        if ticket_num - buy>=0:
            ticket_num = ticket_num - buy
            print("There are currently", ticket_num, "remaining.")
            buyers = buyers + 1
        else:
            print("There are currently", ticket_num, "remaining. You can buy up to", ticket_num, "tickets")
print()

print("The total number of buyers was:", buyers)

这是解决方案。问题是您两次获得输入。首先低于一会儿。其次,在if语句下面。