Home > OS >  How do you end code using either "quit" or hitting enter/ typing nothing?
How do you end code using either "quit" or hitting enter/ typing nothing?

Time:12-08

I need the code to end when I type either "quit" or nothing.

num_of_tik = 0
total = 0
while True:
  age = input("what is the age of the customer? (enter 'quit' when finshed)" )
  if age == "quit" and "":
    if num_of_tik >= 10:
      print("because you bought 10 or more tickets, you get 20% off!")
      total = total*0.8
    print("you bought", num_of_tik,"tickets")
    print("your total is", total, "dollars")
    break
  else:
    age = int(age)
    if age > 18:
      print("your ticket costs $20")
      total = total   20
      num_of_tik = num_of_tik   1
      
    else:
      if age > 13:
        print("your ticket costs $15")
        total = total   15
        num_of_tik = num_of_tik   1
      else:
        if age >= 3:
          print("your ticket costs $10")
          total = total   10
          num_of_tik = num_of_tik   1 
        else:
          print("your ticket is free")
          num_of_tik = num_of_tik   1 

I have tried using if age == "quit" or "": and that didn't work. I have also tried writing a new if statement. I don't know any other ways to make this work.

CodePudding user response:

You are on the right track, but you have a logic error here:

if age == "quit" and "":

This should be:

if age == "quit" or age == "":

In your original form if the user types "quit" then age == "quit" is True, but "" evaluates to False in Python, so your original if statement effectively becomes:

if True and False:

Not good. ;^)

CodePudding user response:

Like @rhurwitz pointed out, your if statement is malformed. That said, Generally when one variable needs to be compared to multiple values in an or-type statement, I prefer to not use 'or' at all:

if age in ("quit", ""):
   #conditional code


CodePudding user response:

There a minor error in the if condition; instead of : if age == "quit" and ""

it should be if age == "quit" or ""

  • Related