How do i break out of my while loop? - python

Doing an assignment, this is my first program so bear with me. I cant get the while loop to end although i have broke it. I need a way to get out of the loop, and what I'm doing isn't working. Any suggestions would be very helpful thank you.
def main(): #Calls the main function
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")

The problem with your code is your indentation. You have told the program to break when the marker_name is an empty string. I am assuming that you would like the code to finish when all three values are correct, so as such the following code should work for you:
def main():
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
main()
I am a little confused why you have used a try and except? What is the purpose of it?

May I ask why the code block is wrapped in the try-except?
Some suggestions:
remove the try-except as you shouldn't be raising any errors
remove the break statement (after marker_name) as the loop should end when the input is valid
ensure the indentation of all the input while-loop code blocks are identical (your formatting is messed up so I'm not sure if you have nested while loops)
Let me know how this works

Well first of all you break out of a while loop in python with break as you did already. You should only break if a condition you set is met in the loop. So lets say you wanted to break in a while loop that counts and you want to break if the number reaches 100, however, you already had a condition for your while loop. You would then put this inside your while loop.
if x == 100:
break
As you have it now you just break in your while loop after a couple lines of code without a condition. You will only go through the loop once and then break every single time. It defeats the purpose of a while loop.
What exactly are you trying to do in this code? Can you give more detail in your question besides that you would like to break in a while loop? Maybe I can help you more than giving you this generic answer about breaking in a loop.

Related

Check for correct user input without exiting loop

I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.

Encountered a problem of creating a function for my little project

Currently I'm making a project and I want to add a function to it. But I have no clue about the problem I encountered recently. So, here's the wrong code of the function I wrote:
user_input = input()
while True:
if user_input == "add_1":
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
elif content_1 != '':
print("You have added the #1 note. Please use other functions.")
user_input = input()
if user_input == "add_2":
print("Start adding your #2 note...")
content_2 = input("Please enter content: ")
elif content_2 != '':
print("You have added the #2 note. Please use other functions.")
user_input = input()
if user_input == "add_3":
print("Start adding your #3 note...")
content_3 = input("Please enter content: ")
elif content_3 != '':
print("You have added the #3 note. Please use other functions.")
user_input = input()
The expected result:
When the user input the string 'add_1',
the system will process:
Start adding your #1 note...
(Next line) Please enter content: (e.g. Write something here)
Then, the content the user input will be stored into the variable 'content_1'.
Next, after the variable 'content_1' is NOT EMPTY, when the user input the string 'add_1', the system will print the message, 'You have added the #1 note. Please use other functions.'
The system will do the similar function according to the other input 'add_2' and 'add_3'.
The situation now is that I can't think of a solution to write a suitable code for the function. Can some programming masters help me with this problem? Thanks a lot.
The code is messy and hard to read, I would suggest sketching out a diagram of how the logic should work out before even opening the computer and writing your first line of code.
The problem lies within the nested if/elif statements. For each option ("add_1", "add_2", "add_3") there should be a while loop which should run for as long as the content_1 is not empty. After the inner loop finishes, the outer loop restarts.
The code should look something like this. Other options should work the same way.
while True:
# take user input at the start of the loop
user_input = input()
# option 1
if user_input == "add_1":
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
# while content_1 is '', ask again
while content_1 == '':
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
print("You have added the #1 note. Please use other functions.")
# similarly for other options
elif user_input == "add_2":
# ...
Further reading:
In some cases the newly added walrus operator (:=) can be useful when checking user input.For more information visit this tutorial
content_1 is not defined till here if you meant user_input change content_1 to >user_input:
elif content_1 != '':
print("You have added the #1 note. Please use other functions.")
user_input = input()
you have similar multiple mistakes
if/elif statement must have else statement at last:
if (CONDITION):
STATEMENTS
elif (CONDITION):
STATEMENTS
else:
STATEMENTS
I'm not sure exactly what you want to do but let's try to find a solution
while True:
user_input = input('What function do you want to use: ')
if user_input == "add_1":
print("Start adding your #1 note…")
content_1 = input("Please enter content: ")
if content_1 != '':
print("You have added the #1 note. Please use other functions.")
elif user_input == "add_2":
print("Start adding your #2 note…")
content_2 = input("Please enter content: ")
if content_2 != '':
print("You have added the #2 note. Please use other functions.")
elif user_input == "add_3":
print("Start adding your #3 note…")
content_3 = input("Please enter content: ")
if content_3 != '':
print("You have added the #3 note. Please use other functions.")
But we could simplify this solution:
content = {}
while True:
user_input = input('What function do you want to use: ')
if user_input.startswith("add_") and len(user_input) == 5:
note_number = user_input[4]
if note_number in ('1', '2', '3'):
print(f"Start adding your #{note_number} note…")
content[note_number] = input("Please enter content: ")
if content[note_number]:
print(f"You have added the #{note_number} note. Please use other functions.")
Is that you wanted to do?

When I run the program it asks for my input multiple times even after I've entered it once already

When I run the program it asks for my input multiple times even after I've entered it once already.
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
Asks the user to input a name which is the key to a value, which it returns
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
You need to ask the user input first instead of comparing the user input directly to the key.
You do not want to do it like that. Take a look at the following instead:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
You do not have to loop through your dict and check the user input against each value individually (plus you are forcing the user to update\re-enter his input continuously).
Just receive it once and process it.
If you want to keep the loop running to allow for multiple queries, use while like so:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")

Continue isnt working properly

I do need help in solving my code.
Below python code 'continue' is not working properly
dicemp = {'12345':''}
while(1):
choice = int(input("Please enter your choice\n"))
if (choice == 1):
empno = input("Enter employee number: ")
for i in dicemp.keys():
if i == empno:
print("employee already exists in the database")
continue
print("Hello")
Output:
Please enter your choice
1
Enter employee number: 12345
employee already exists in the database
Hello
So for the above code if I give same employee no. 12345 it is going into if block and printing the message"employee already exists in the database" after this it should continue from start but in this case it is also printing "hello".
Your continue is moving the for loop on to its next iteration, which would have happened anyway. If you need to continue the outer loop, you can do something like this:
while True:
choice = int(input("Please enter your choice\n"))
if choice == 1:
empno = input("Enter employee number: ")
found = False
for i in dicemp:
if i == empno:
print("employee already exists in the database")
found = True
break
if found:
continue
print("Hello")
Now the continue is outside the for loop, so it will continue the outer loop.
You could simplify this to:
while True:
choice = int(input("Please enter your choice\n"))
if choice==1:
empno = input("Enter employee number: ")
if empno in dicemp:
print("employee already exists in the database")
continue
print("Hello")
and get rid of the inner loop entirely.

While loop not repeating once information in entered

Making a program which has a list of the different star signs, then asks the user to enter what star sign they are and then for the program to check that is contained in the list before moving on.
The problem is that it does check that it is in the list, but it does not repeat.
play = True
while play:
print("Welcome to my Pseudo_Sammy program, please enter your name, star sign and then your question by typing it in and pressing the enter key, and I will give you the answer to your question")
name = input("What do they call you? ")
starsigns = ("leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces", "aries", "taurus", "gemini", "cancer")
starsign = str(input("What star do you come from? ")).lower()
while True:
try:
if starsign in starsigns:
break
else:
raise
except:
print("Please enter a valid star sign")
question = input("What bothers you dear? ")
if you want to repeat an input until you get a valid answer and THEN ask the next question, you need to place the 1st input inside while loop and the 2nd input outside the loop, like this:
starsigns = ("leo", "virgo", ...)
starsign = None
while starsign not in starsigns:
if starsign:
print("Please enter a valid star sign: {}.".format(", ".join(starsigns)))
starsign = input("What start do you come from? ").lower().strip()
question = input("What bothers you dear? ")

Categories