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.
Related
I'm a student who is doing my Python assignment. Thing is, our lecturer is really strict on us not using python built ins and also refuses to check our code before submission and I'm having the hardest time trying to get my code to work properly during registration.
My problem currently is that I want the code to prompt an error from the program itself when the user tries to register with a taken username. However, it keeps running different errors regardless of how I try to fix it. Can anyone please point me in the right direction or tell me what's wrong with my code? I'd be really grateful for any help.
def grant():
print("Helllooooo")
def begin():
while True:
print("Welcome to the Freshco Groceries App!")
option = input("Are you a new or returning user?\n"
"Enter 1 if you would like to LOGIN\n"
"Enter 2 if you would like to register\n"
"Enter 3 if you would like to exit the program\n")
if option=="1":
access(option)
break
elif option=="2":
access(option)
break
elif option=="3":
print("Thank you! Have a good day.")
exit()
else:
continue
def access(option):
if(option=="1"):
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
login(name,password)
else:
print("First step: Please choose a username and a unique password.")
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
register(name,password)
newuser()
def login(name,password):
success=False
file = open("user_details.txt","r")
for line in file:
a,b = line.split(",")
if (name in a) and (password in b):
success=True
break
file.close()
if(success):
print("You have successfully logged in! Happy shopping!")
grant()
else:
print("Wrong username or password entered.")
def register(name,password):
exist = False
while True:
file = open("user_details.txt", "r")
for line in file:
line = line.rstrip()
if (name == line):
exist = True
break
else:
pass
file.close()
if (exist):
print("Username has been taken. Please try again with a new one.")
break
else:
file = open("user_details.txt","a")
file.write("\n" + name + "," + password)
print("You have successfully registered! Welcome to the Freshco Family!")
grant()
break
def newuser():
print("Before you start using the app, please fill in the details below.")
alldata = []
while True:
newdata = []
nname = input("Please enter your full name:\n")
newdata.append(nname)
while True:
ngender = input("Are you female or male?\n"
"1: female\n"
"2: male\n")
if ngender=="1":
fingender="female"
newdata.append(fingender)
break
elif ngender=="2":
fingender="male"
newdata.append(fingender)
break
else:
print("INVALID INPUT")
continue
naddress = input("Please enter your address:\n")
newdata.append(naddress)
nemail = input("Please enter your email address:\n")
newdata.append(nemail)
ncontact = input("Please enter your contact number:\n")
newdata.append(ncontact)
ndob = input("Please enter your dob in this format: <DD.MM.YY>\n")
newdata.append(ndob)
alldata.append(newdata)
print(newdata)
break
print("Thank you for entering your information, you will be redirected now!")
grant()
begin()
thank you so much! T-T
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)
I am trying to get the user to input either 1, 2, or 3. If none of the numbers are entered an error message will be displayed and the program will ask for input again.
How do i identify if what the user typed is either 1,2, or 3?
This is what i currently have.
while True:
try:
userInput = input("Enter a number: ")
if userInput not in range(1,4):
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
elif userInput.isdigit('1'):
print('1')
elif userInput.isdigit('2'):
print('2')
else:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
If you want your input to be in range(1, 4), it needs to be an int, not a str (which is what's returned by input():
while True:
try:
userInput = int(input("Enter a number: "))
assert userInput in range(1, 4)
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
if userInput == 1:
print('1')
if userInput == 2:
print('2')
if userInput == 3:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
break
You have to check values of the same type. Your code compares string and int. You also need to work on the syntax of basic statements: if <condition>: except: isn't legal. Keep it simple:
userInput = None
while userInput not in ['1', '2', '3']:
userInput = input("Enter a number: ")
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.
Why is the loop failing to terminate when meeting the required conditions.
I would appreciate an in-depth explanation rather than the code being corrected for me.
def get_name(name_type):
return raw_input("Please enter you're {}name: \n".format(name_type))
def UserName():
result = get_name("Fore"), get_name("Middle"), get_name("Sur")
return " ".join(result)
print("You're UserName is : " + UserName())
while True:
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="no":
break
Your break statement is nested within the inner while loop, so it is breaking that loop rather than the while True loop. I think moving the conditional statement out of the inner loop and changing the logic to if discont=='yes' (note: renamed var to more accurate description) will give you what you want:
while True:
...
discont = raw_input("Would you like to quit? yes/no > ").lower()
while discont not in ("yes","no"):
discont = raw_input("Would you like to quit? yes/no > ").lower()
if discont=="yes":
break
Now it does:
def get_name(name_type):
return raw_input("Please enter you're {}name: \n".format(name_type))
def UserName():
result = get_name("Fore"), get_name("Middle"), get_name("Sur")
return " ".join(result)
print("You're UserName is : " + UserName())
print
cont = 'no'
while cont != 'yes':
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="yes":
break
You're inside two while loops. You want to break out of both if the user wants to exit, otherwise only out of the inner one: Move the condition out of the while loop, then it should work:
from sys import exit
...
while True:
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="yes":
break
The next piece of advice has nothing to do with your question, but I'll give it anyways: There's no need to define the Base, Power, and Result functions in every loop iteration. Just assign the values to variables and print directly:
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
print base*power