Python loop from begining without running again the code - python

I don't know how I'm supposed to loop this code from the beginning without running the code again. I know I should put while True():
list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
name = input("Type name to check: ")
if name in list_of_students:
print("This student is enrolled.")
elif name not in list_of_students:
print("This student is not enrolled.")
while True:
If I don't want to duplicate the code, what should I do?

While True should be sufficient to have that input test run repeatedly.
while True:
name = input("Enter a name to check: ")
if name in list_of_students:
print("This student is enrolled")
else:
print("This student is not enrolled")

Are you looking to create a program that infinitely accepts a search argument?
If so the code would look like so:
list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
while True:
name = input("Type name to check: ")
if name in list_of_students:
print("This student is enrolled.")
else:
print("This student is not enrolled.")
Otherwise please further explain the problem.

list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
def student_checker(name):
if name == list_of_students:
print("This student is enrolled.")
elif name not in list_of_students:
print("This student is not enrolled.")
# Test to make sure it is working, comment out when not wanted
student_checker("Michele")
student_checker("Anthony")
while True:
name = input("Type name to check: ")
NOTE: this will run continuously, please make sure to add a breaking condition when you want the code to finish.

Related

Python : How to check if input is not equal to any item in a 2d array?

I was trying to check if the username entered is equal to the second index of item in the list, and I tried to use !=, but it still keeps letting the same username to be registered. What's the problem with the code ?
Registering username :
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name != user[1]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)
Editted:
The results of != and == seems to be different, the == works.
Login username :
user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name == user[1]:
break # break out for loop
else:
print("Unregistered username")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Logged in as",name)
You're very close!
What you're trying to do: break out of the loop if there are any names in user_list that match the new name.
What it's currently doing: breaking out of the loop if there are any names in user_list that don't match the new name.
I.e., if you enter Daniel, since Daniel != Raymond, you will break early.
Instead, what you should do is break if the newly entered name is not present in a list of names:
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
if name in [user[1] for user in user_list]: # existing names list
print("This username has been registered")
name = input("Please try another username : ")
else:
break
print("Username registered as",name)
This code below will sort a lot of things out. In your code, even if we fix the indentation mistake with the else which should be moved into the for loop, the code won't work if we type Raymond. So I have provided an example which checks if the entered usr is in all the names in your user_list.
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]
name = input("Please enter your name : ")
while True:
if name == '':
name = input("Please enter your name : ")
else:
for user in user_list:
if name not in [lst[-1] for lst in user_list]:
break # break out for loop
else:
print("This username has been registered")
name = input("Please try another username : ")
continue # continue the while loop
break # break out while loop
print("Username registered as",name)

How do i break out of my while loop?

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.

Use of continue in python - how to break out of an individual loop?

I have written some code that contains several while loops.
answer = "yes"
while answer == "yes":
name = input("what is your name?")
while len(name) > 0 and name.isalpha():
print("okay")
break
else:
print("error")
continue
job = input("what is your job?")
while job.isalpha():
print("great")
else:
print("not so great")
continue
age = input("how old are you?")
while age.isnumeric():
print('nice')
else:
print("not so nice")
continue
What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.?
Thank you.
You can use while True because answer never change.
It's useless while for 1 expression and 1 break.
You should put everything on a while True and check:
while True:
name = input("what is your name?")
job = input("what is your job?")
if len(name) > 0 and name.isalpha() and job.isalpha():
print("great")
break
print("error")
I moved the question into a seperate fuction to de-duplicate the code. It will ask again and again as long as the answer is not satisfactory.
def ask(s):
r = ""
while not r or not r.isalpha():
r = input(s)
return r
name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))

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.

Function loop True or False

I am now learning functions in python. I came across an exercise that asks me to write a script that will tell the user that the student is in a class or not. Here is the result that the script should present:
Welcome to the student checker!
Please give me the name of a student (enter 'q' to quit): [student1]
No, that student is not in the class.
Please give me the name of a student (enter 'q' to quit): [student2]
Yes, that student is enrolled in the class!
Please give me the name of a student (enter 'q' to quit): q
Goodbye!
I have written a script that fulfills the requirements. Here is the script:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
But the exercise states that there should be a function that returns True if the student is present, and False if not.
Could anybody enlighten me on how can I change my script to fulfill the requirement of adding a function that returns True if the student is present, and False if not?
Thanks in advance!! Peace!!!
Try doing something like this:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
def is_present(name_student):
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
return True
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
return False
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
is_present(name_student)
Wrap the logic into a function, so it can return a value, and call it each time your infinite loop iterates.
#edit
#barak manos is right, I updated the code
The following is one way to convert the student test into a function:
def student_present(student):
return student in ['Andreas', 'Martina', 'Maria']
print "Welcome to the student checker!"
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if student_present(name_student):
print "Yes, {} is enrolled in the class!".format(name_student)
else:
print "No, {} is not in the class.".format(name_student)
Note student in [xxxxxx] automatically gives you a boolean result which can be returned directly. There is no need to explicitly return True and False.
Another point to consider, what happens if martina is entered? Using the current code it would state not in class. If you changed the function as follows, it would also accept this:
def student_present(student):
return student.lower() in ['andreas', 'martina', 'maria']

Categories