python "break" error: break outside loop - python

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.

Related

How to stop code running when if statement is not fulfilled

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()

Combine multiple while statements python

So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
while True:
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
If I combine them and someone types a A-Z character with 'age' then the code restarts all over without having saved the 'name' statement. I would like it to save 'name' if it's correct and only start over from the if statement that was false.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
Use a function to encapsulate asking for information. You can pass in a validation test function:
def ask(question, validator, errormessage):
while True:
result = raw_input(question)
if not validator(result):
print(errormessage)
continue
return result
name = ask("NAME PLEASE\n", lambda s: s.isalpha(), "Please chars dude")
age = ask("Please type your age\n", lambda s: s.isdigit(), "Please digits only")
This is far more readable then any number of tests to see if the user already entered a correct name and you only need to ask for the age now.
Why not use functions and cut down on some duplication in the process?
def ask_input(prompt, error_msg, validation_fn):
while True:
data = raw_input(prompt)
if validation_fn(data):
return data
print(error_msg)
name = ask_input("NAME PLEASE\n", "Please chars dude", lambda x: x.isalpha())
age = ask_input("Please type your age\n", "Please digits only",
lambda x: x.isdigit())
In this case, the prompt (what to ask the user), an error message (what to provide on invalid input), and a validation function are provided to the ask_input() function. This hides the while loop behind the function call and gives you something more meaningful to read in the code.
The lambda functions are just an easy way to help do the validation. You could do this instead:
def isalpha(x):
return x.isalpha()
def isdigit(x):
return x.isdigit()
name = ask_input("NAME PLEASE\n", "Please chars dude", isalpha)
age = ask_input("Please type your age\n", "Please digits only", isdigit)
You can set the variables to None first, and then check them before assignment:
name, age = None, None
while True:
if name is None:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha():
print("Please chars dude")
name = None
continue
if age is None:
age = raw_input("Please type your age\n")
if not age.isdigit():
print("Please digits only")
age = None
continue
print("input is valid")
break
continue will start the loop over again. This fits better in the logic of your code, since break actually stop and exit the loop code.
Just use flags to track weather valid input is given, if given then exit the loop.
name_input_required = True
name = ''
while name_input_required:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
name_input_required = False
else:
print("Please chars dude")
age_input_required = True
age = None
while age_input_required:
age = raw_input("Please type your age\n")
if age.isdigit():
age_input_required = False
else:
print("Please digits only")
Try this:
name = None
age = None
while requires_info:
if name is None:
temp_name = str(raw_input("NAME PLEASE\n"))
if temp_name.isalpha():
name = temp_name
continue
else:
print("Please chars dude")
continue
if age is None:
temp_age = raw_input("Please type your age\n")
if temp_age.isdigit():
age = temp_age
continue
else:
print("Please digits only")
continue
break
What we do here is use a single continuous loop and a few if statements/variables to track what still needs to be done. Note depending on how you want them to enter the data you may also add logic to not ask for age if the name was invalid.
So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
I assume the actual problem is "How to reduce tiresome code?" instead of "How to merge two loops into one?". I think keeping two loops is a good idea.
def safe_input(prompt, err_message, validation_fn):
while True:
value = raw_input(prompt)
if validation_fn(value):
return value
print err_message
name = safe_input("NAME PLEASE\n", "Please chars dude", str.isalpha)
age = safe_input("Please type your age\n", "Please digits only", str.isdigit)
If you always want the used to enter text in a separate line, you might want to print prompt before raw_input and to not give an argument to raw_input. That way you don't have to supply "\n" in every call of safe_input.
Yes, you can combine both loops in one loop!
Always try to solve the problem line by line.
You will get to learn the language better and it is the most simple way to solve any problem too.
A line by line solution would look like this:
name = '' # define name outside while loop
while True:
if not name:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha(): # validate name
print("Please chars dude")
# reset name
name = ''
else:
age = raw_input("Please type your age\n")
if age.isdigit(): # validate age
"""continue your code here"""
print('name: ' + name + ' and age: ' + age)
print('Ok! Goodbye!')
break # while loop
else:
print("Please digits only")
will print:
NAME PLEASE
Elis
Please type your age
30
name: Elis and age: 30
Ok! Goodbye!
This will help you understand while loop better and how to use it in more difficult cases.
Do not over design using redundant language features. It will make refactoring and debugging difficult.

'invalid literal for an int' when trying to convert an input string to an int [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I have tried making the input an integer but if I put a letter in I get the 'invalid literal for an int'
Please could you help.
def agecheck():
quit_menu = False
while quit_menu is False:
age = input("\nEnter your age: ")
if age >= "18":
print("You are the correct age.")
elif age < "18":
print("Get off this website.")
else:
print("Enter a correct integer.")
quit_menu = True
agecheck()
Both the input and what you're comparing it to should be integers if using operators like >= or <. Additionally, I suspect you actually want to quit the menu if the input is valid as opposed to invalid, and continue looping until the user enters an integer. You should also make your code exception safe in the event that something is entered that cannot be cast as an int. Try the following:
def agecheck():
quit_menu = False
while quit_menu == False:
try:
age = int(input("\nEnter your age: "))
if age >= 18:
print("You are the correct age.")
elif age < 18:
print("Get off this website.")
quit_menu = True
except:
print("Enter a correct integer.")
agecheck()
Here's something you can try -
def agecheck():
ans = input("\n Enter your age: ")
try:
age = int(ans)
if age >= 18:
print("You are the correct age.")
elif age < 18:
print("Get off this website.")
else:
print("Enter a correct integer.")
except ValueError:
print("That wasn't a number")
for i in range(3):
agecheck()
It runs three times, enter the inputs 4, 20, and "a", and notice the logs.

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.")

coding error msg for typing 'enter'

Let's say you're asked for input, such as your age, but instead of putting your age in, you accidentally hit 'enter.' The program, however, ignores the keystroke and goes to the next step. Your age is not entered but is regarded as empty/null value.
How do you code to fix this problem?
Thank you
With a while loop, you do not need to write the input() function twice:
while True:
age = input('>> Age: ')
if age:
break
print('Please enter your age')
You might also check if the input is an integer and get an integer from the string. An empty string for age will also raise a ValueError exception:
while True:
try:
age = int(input('>> Age: '))
except ValueError:
print('Incorrect input')
continue
else:
break
age = raw_input("Age: ")
while not age: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error!"
age = raw_input("Age: ")
You can create a wrapper function for this.
def not_empty_input(prompt):
input = raw_input(prompt)
while not input: # In Python, empty strings meet this condition. So does [] and {}. :)
print "Error! No input specified."
input = raw_input(prompt)
return input
Then:
address = not_empty_input("Address: ")
age = not_empty_input("Age: ")

Categories