I'm having trouble breaking out of the nested while loop in my code completely. How do I break out of two loops? Here's my attempt:
while continue_enter == True:
while True:
try:
enter_result_selection = int(input("What test would you like to enter results for? Please enter a number - Reading Test: 1 Writing Test: 2 Numeracy Test: 3 Digital Literacy Test: 4 All Tests: 5 - "))
if enter_result_selection == 1:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 2:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 3:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 4:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 5:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
else:
print("Sorry, this is an invalid number. Please only enter numbers ranging from the values 1 - 5.")
break
except ValueError:
print("Sorry, your input was invalid. Please enter a number and try again.")
while continue_enter == True or continue_enter == False:
ask_continue_enter = input("Would you like to enter results for another student? ")
if ask_continue_enter.lower() == "yes" or ask_continue_enter.lower() == "y":
continue_enter == True
break
elif ask_continue_enter.lower() == "no" or ask_continue_enter.lower() == "n":
continue_enter == False
break
else:
print("Sorry, this is an invalid input. Please enter with 'Yes' or 'No'")
if continue_enter == True:
continue
elif continue_enter == False:
break
Here is an example of how to break out of nested loops using exceptions:
class MyException(Exception):
pass
x=1
y=1
try:
while x<10:
y=1
while y<10:
if x==5 and y==5:
raise MyException
y=y+1
x=x+1
except MyException:
print x
print y
Output:
$ python prog.py
5
5
You don't HAVE to define an own exception. You can just use the standard ones, or even just use raise Exception('Something happened'). However, I would STRONGLY advice not to do that. See this link for more info: https://stackoverflow.com/a/24065533/6699433
EDIT:
I just read that you can use the builtin exception StopIteration. That seems suitable.
Related
i tried everything shoould i add something in between or what i used to work with c++
so i dont know what to do
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == "1":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
If I understood correctly, you have an indentation problem, as well as condition one.
Every input from the console is treated as a string.
You converted that input to int and then checked against the string, it isn't equal.
The right one would be:
start = input("please choose what u want: ")
if start == "1":
or
start = int(input("please choose what u want: "))
if start == 1:
Also, make sure to indent the code:
if start == "2":
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
You should write your code inside the if statement like this:
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (
choose+chose))
if start == 2:
print("enter your first number")
choose = float(input("please enter
your first number: "))
chose = float(input("please enter
your second number: "))
print("your answer is ", (choose -
chose))
Try:
print("1 add")
print("2 sub")
print("3 mult")
print("4 div")
start = int(input("please choose what u want: "))
if start == 1:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose + chose))
elif start == 2:
print("enter your first number")
choose = float(input("please enter your first number: "))
chose = float(input("please enter your second number: "))
print("your answer is ", (choose - chose))
The data you get from the user is integer, but the type you are querying is string. Your code is not working due to data type mismatch. I have specified the correct code above.
I would like for the input to remember the first number given to it even if you type something silly on the second input. While right now obviously the loop starts again and asks for both of the inputs again. Is there an easy way to do this?
Calculator
Give a number: 124
Give a number: dwa
This input is invalid.
Give a number: 12
Give a number:
while I would like it to do this:
Calculator
Give first number: 124
Give second number: dwa
This input is invalid.
Give second number: 12
And this is the entire code:
import math
import sys
print("Calculator")
def main():
while True:
try:
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
while True:
print('(1) +')
print('(2) -')
print('(3) *')
print('(4) /')
print('(5) sin(number1/number2')
print('(6) cos(number1/number2)')
print('(7) Change numbers')
print('(8) Quit')
print(f'Current numbers are: {kek1} {kek2}')
kaka = input("Please select something (1-6):")
plus = kek1 + kek2
minus = kek1 - kek2
times = kek1 * kek2
divide = kek1 / kek2
sin = math.sin(kek1/kek2)
cos = math.cos(kek1/kek2)
if kaka == "1":
print(f'The result is: {plus}')
if kaka == "2":
print(f'The result is: {minus}')
if kaka == "3":
print(f'The result is: {times}')
if kaka == "4":
print(f'The result is: {divide}')
if kaka == "5":
print(f'The result is: {sin}')
if kaka == "6":
print(f'The result is: {cos}')
if kaka == "7":
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
if kaka == "8":
print("Thank you!")
sys.exit(0)
except SystemExit:
sys.exit(0)
except:
print("This input is invalid.")
if __name__=="__main__":
main()
If you have any ideas on how to do this it would be a great help.
Use separate try statements for each input with their own loops
while True:
try:
kek1 = input("First number")
kek1 = int(kek1)
break
except:
print("Invalid")
continue
while True:
try:
kek2 = input("Second number")
kek2 = int(kek2)
break
except:
print("Invalid")
continue
And then go into the rest of your loop.
Sorry for a brief answer but I'm on my phone :P
instead of using try catch, you may use .isnumeric() :
kek1 = input("First number")
while not kek1.isnumeric() :
print("This input is invalid.")
kek1 = input("First number")
kek1 =int(kek1)
kek2 = input("First number")
while not kek2.isnumeric() :
print("This input is invalid.")
kek2 = input("Second number")
kek2 =int(kek1)
Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)
I am creating a program where you will have to loop through multiple questions each with a condition. If user input for the question does not meet the requirement, it will print out the error and prompt user to re-enter. Else, it will continue with the next question. And not only prompting user to re-enter after all 3 questions are answered.
This it the output I am getting now:
while True:
amount = int(input("Enter amount: "))
rate = int(input("Enter rate: "))
year = float(input("Enter year: "))
if amount<4000:
print("Invalid amount")
continue
elif rate<0:
print("invalid rate")
continue
elif year<0:
print("invalid year")
break
Output:
Enter amount: 1
Enter rate: 3
Enter year: 4
Invalid amount
Enter amount:
Expected output:
Enter amount: 4
Invalid amount
Enter amount:
It's not very clear what are you trying to achieve, but I think you want this:
while True:
amount = int(input("Enter amount: "))
if amount < 4000:
print("Invalid amount")
continue
break
while True:
rate = int(input("Enter rate: "))
if rate < 0:
print("invalid rate")
continue
break
while True:
year = float(input("Enter year: "))
if year < 0:
print("invalid year")
continue
break
This will only ask to re-enter the invalid values.
Another more reusable method would be:
def loop_user_input(input_name, meets_condition):
while True:
value = int(input(f"Enter {input_name}: "))
if not meets_condition(value):
print(f"Invalid {input_name}")
else:
return value
loop_user_input('amount', lambda val: val < 4000)
loop_user_input('rate', lambda val: val < 0)
loop_user_input('year', lambda val: val < 0)
Here you have a loop that only returns when the input value meets the condition, that you pass in. I recommend you check your conditions, because a year normally shouldn't be negative (rate < 0). Also your solution throws an exception, if the user enters something else then an int. Maybe add a try-catch to your solution:
try:
value = int(input(f"Enter {input_name}: "))
except:
print(f"Invalid {input_name}")
continue
What I'm trying to do is ask users for two inputs, if one of the inputs is less than zero or if the input is some string then ask for the inputs again. The only valid input are numbers >=0. So you can't have something like -1 or cat as inputs.
Attempt 1:
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
while int(number_of_books) < 0 or int(number_of_chairs) < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
But from this I realized that the input are always strings so it will ask for input again.
Attempt 2:
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
while number_of_books < 0 or number_of_chairs < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
But with this one I realized that you cannot do int('some string')
So I'm wondering if there is a way to do this or is this something not possible?
You should use a while loop for each input, so only the invalid one is asked again. By using while True, you ask for input once, and break once it's valid. Try to convert to int, which raises ValueError if that cannot be done. Exceptions cause the custom error to be printed, and the loop restarted.
while True:
books_input = input("What is the number of books in the game?: ")
try:
number_of_books = int(books_input)
if number_of_books < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
You'd need to do this for each input (maybe there are more than two?), so it makes sense to create a function to do the heavy lifting.
def non_negative_input(message):
while True:
input_string = input(message)
try:
input_int = int(books_input)
if input_int < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
return input_int
Calling it:
non_negative_input("What is the number of books in the game?: ")
The solution is to coerce the answer to int() and catch any exceptions, for example:
while True:
try:
number_of_books = int(raw_input('Enter number of books:'))
if number_of_books < 0:
raise ValueError('must be greater than zero')
except ValueError, exc:
print("ERROR: %s" % str(exc))
continue
break
Probably you should put this in a function, and make the prompt a variable (to allow re-use).
Use the try except method
while stringval = input("What is the number you want to enter"):
try:
intval = int(stringval)
if intval > -1:
break
except ValueError:
print 'Invalid answer, try again'
# Process intval now