How to stop code running when if statement is not fulfilled - python

I am doing a school project and what i want to add is a line of code that would stop the code from running if age < 15 or if age > 100
I tried break but it would continue to the next line.
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
if age < 15:
print("sorry you are too young to enter the store!")
break
if age > 100:
print("Please come back in the next life")
break
else:
break
print("")
print("Welcome to Jim's Computer Store", name)
print("") while True:
try:
cash = int(input("How much cash do you currently have? $"))
except ValueError:
print("Please enter a valid value! ")
continue
else:
break

I would advise you to proceed step by step. The code in the question is too long for the purpose. When the first step behaves like you want, you can do another step.
Is is this working like you want ?
name = "John"
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
break
# Here, we can assume that 'age' is an integer
if age < 15:
print("sorry you are too young to enter the store!")
exit()
if age > 100:
print("Please come back in the next life")
exit()
print("")
print("Welcome to Jim's Computer Store", name)
# When the code above will be validated, the next step will be easy
The while loop is to assure that age is an integer when he breaks the loop (if age is not an integer, the program will execute the continue instruction and go back to the start of the loop).

Just adding a exit() after the if condition will do the job.
An example would be:
x = 5
if x < 2:
print "It works"
else:
exit()
Or without the else statement:
x = 5
if x < 2:
print "It works"
exit()

Related

(Python 3.2):Exit when an if statement doesn't meet a condition

I'm new to Python. I'm writing a program that initially asks for a user's information (name, age, etc.) and I'm trying to figure how to exit the problem if the user's age is under 7. Here is my code so far.
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
break
except:
print("Please enter a number")
At first I tried adding an exit() statement after the print following the elif statement, but I realize that instead of exiting, the program will just loop back to the first input requesting the user's age. How can I make it so that the program will terminate, so an underage player can't progress?
Thanks everyone!!
The code you gave works fine when I do this:
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
break
except:
print("Please enter a number")
age_func()
However, if you put the function call inside a loop,
while True:
age_func()
it will not work. I'm guessing that is what happened. You can solve by using sys.exit():
import sys
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
sys.exit() #replaced break with sys.exit()
except:
print("Please enter a number")
while True:
age_func()
The try... except is catching the exception raised by exit().
A better solution is to not use a catch-all except, and instead to use except ValueError, which will only catch specific errors.
Please read entire post :)
The solution to killing a program is using 'sys.exit()'. So, you would do this:
import sys
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
sys.exit() #replaced break with sys.exit()
except:
print("Please enter a number")
age_func()
Unfortunately, this still does not work, because of your try statement. Exits are considered as errors, so when you try to run 'sys.exit()', it sends "Please enter a number", even if what you typed was a number. This is why it is important to specify the exception type, like this:
import sys
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
sys.exit() #replaced break with sys.exit()
except ValueError: #Now it will only except if what you typed wasn't a number, so it will exit properly.
print("Please enter a number")
age_func()
Hope this helps
There is no need to check elif statement because it is understood, if if age>7 false then it means age will always less than 7 or 7.
def age_func():
while True:
age = int(input('How old are you? '))
if age > 7:
print(f'OK! You are {age} years old')
else:
print("Too young for this game. Come back in a few years.")
break
import sys
def age_func():
while True:
try:
age = int(input('How old are you? '))
if age > 7:
print('OK! You are {age} years old')
elif age < 7:
print("Too young for this game. Come back in a few years.")
sys.exit()
except ValueError:
print("Please enter a number")
age_func()

Having user input take string and int? (Python)

prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?
I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.
If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.
prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True:
if user_input == 'quit':
break
age = int(user_input)
if age < 3:
price += 5
elif age < 12:
price += 10
else:
price += 15
print(f"Your ticket is ${price}")
user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")

python "break" error: break outside loop

When I was developing my first code I faced a problem which with the break command which I tried to use to restart the program if there's an error.
Take a look on the code maybe you would understand better.
Name = str(input("Please enter Your Name:"))
Age = input("Please enter your age: ")
if Age != int():
print ("Error! Check the age")
break
elif Age == int():
continue
Height = input("Please enter your height: ")
if Height != int():
print ("Error! Check the Height")
break
elif Height == int():
continue
if Age == int() and Age >= 18 and Height == int() and Height >= 148:
print("You're able to drive a car " + (Name) )
elif Age == int() and Age < 18 and Height == int() and Height > 148:
print("You're not able to drive a car " + (Name) )
elif Age and Height != int() :
print ("Error! , Age or Height are not numbers")
error:
"C:\Users\Ghanim\Desktop\Coding\Documents\Projects\Python\Project1\Project1.py", line 6
break
^
SyntaxError: 'break'
outside loop
The break statement is used to exit loops, not the program. Use sys.exit() to quit the program, you'll need to import sys too.
EDIT:
In answer to your comment, this is how I'd probably do it:
while True:
inputted_name = input("Please enter your name:")
try:
name = str(inputted_name)
except ValueError:
print("Please enter a valid name")
else:
break
while True:
inputted_age = input("Please enter your age:")
try:
age = int(inputted_age)
except ValueError:
print("Please enter a valid age")
else:
break
while True:
inputted_height = input("Please enter your height:")
try:
height = float(inputted_height)
except ValueError:
print("Please enter a valid height")
else:
break
if age >= 18 and height >= 148:
print("You're able to drive a car {}".format(inputted_name))
if age < 18 and height > 148:
print("You're not able to drive a car {}".format(inputted_name))
So there are a few changes:
Each stage of the user input is in its own loop. I've used try/except/else statements which try to cast the input to the correct type, except ValueErrors (thrown if it cant be cast, which will happen if the user puts a text answer to the input age for example. If it casts to the correct type successfully, the loop is broken and the script moves onto the next one. Having separate loops for each one means if the user puts in an incorrect value for one of them, they don't have to redo the whole thing.
I've also used format() to insert name into the final strings to avoid having to do string concatenation.
Also, just a quick note, I'm assuming you're using Python 3 for this. However, if you're using Python 2 input() should be replaced with raw_input(). In Python 2 input() will try and evaluate the user input as an expression, whereas raw_input() will return a string.
The break statement breaks out of a loop (for-loop or while-loop). Outside of this context it does not make sense.
break cannot restart your program, break can only be used in loop such as for or while.
In you case, just use exit(-1)
there is no loop in your program. break can't be used outside a loop. You can use sys.exit() instead of breakand pass instead of continue.

Getting error message when trying to break out of a while loop in Python

I'm trying to write code that includes the following:
1) Uses a conditional test in the while statement to stop the loop.
2) Uses an active variable to control how long the loop runs.
3) Use a break statement to exit the loop when the user enters a 'quit' value.
Here is my code:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"
Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.
You are converting the user's input to a number before checking if that input is actually a number. Go from this:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
To this:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
This will check for a request to exit before assuming that the user entered a number.
You convert age to an integer with int() so it will never equal 'quit'. Do the quit check first, then convert to integer:
age = input(prompt)
if age == 'quit':
break;
age = int(age)
...
This now checks if it's equal to a string literal first, so that in the case it is, it breaks correctly. If not, then continue on as usual.
You are casting the string "quit" to integer, and python tells you it's wrong.
This will work :
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
Just for the sake of showing something different, you can actually make use of a try/except here for catching a ValueError and in your exception block, you can check for quit and break accordingly. Furthermore, you can slightly simplify your input prompt to save a couple of lines.
You can also force the casing of quit to lowercase so that you allow it to be written in any casing and just force it to a single case and check for quit (if someone happens to write QuIt or QUIT it will still work).
while True:
age = input("What is your age?\nEnter 'quit' to exit: ")
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
except ValueError:
if age.lower() == 'quit':
break
As proposed in a comment above you should use raw_input() instead of input in order to handle the user input as a string so that you can check for the 'quit' string. If the user input is not equal to 'quit' then you can try to manage the input string as integer numbers. In case the user passes an invalid string (e.g. something like 'hgkjhfdjghd') you can handle it as an exception.
Find below a piece of code that demonstrates what I described above:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
except Exception as e:
print 'ERROR:', e
print("Please enter a valid age.")

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories