I wrote this code that I'm trying to get it to work. What I am trying to do is to prompt user to enter names of employees and use a list to store the names.
Now the part that I am having trouble with is with the loop, the loop is suppose to stop when the user types 'done', and then display the number of names entered, and with another loop, display the names entered each on its own line.
I don't know what I am doing wrong with the code but, after the user enters then names it will say: 'Press enter to continues adding names' and it will also say: 'If you would like to stop adding names, type=done'
If the user hits enter, then it should ask for another name and repeat the questions to see if user wants to add more or stop. But for some reason, even if the user press enter to continue adding names, it still outputs the number of names entered and the list of names. I don't want that to happen, I'm trying to get it to where it will display the result ONLY if the user types 'done' but the word 'done, cannot be displayed in the output. I've looked over and over the code and can't figure out what if am doing wrong.
Here is my code:
employee_list=[]
stop='done'
while stop == 'done':
employee_name=input('Enter name of employee:')
employee_list.append(employee_name)
print('Press enter to continues adding names')
enter_another=input('If you would like to stop adding names, type=done ')
print()
list_size=len(employee_list)
print('The number of employees you have entered: ', list_size)
for index in range(list_size):
print(employee_list[index])
You haven't got a check in your code if a person types done.
For example:
if enter_another == "done":
stop == "finished now"
But this doesn't make sense, your check is saying "if stop is done then keep going", which makes no sense semantically.
Try this instead:
more_employees = True
while more_employees: # Never do thing == True
# ... your code
enter_another=input('If you would like to stop adding names, type=done ')
if enter_another == "done":
more_employees = False
# ... the rest of your code
As stated, PEP8 recommends against comparing thing == True:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
Try this. I have put your printing condition outside the loop.
employee_list=[]
stop='done'
while stop == 'done':
employee_name=raw_input('Enter name of employee: ')
employee_list.append(employee_name)
print 'Press enter to continue adding names'
enter_another=raw_input('If you would like to stop adding names, type=done \n')
if enter_another == 'done':
stop = 'random'
print
list_size=len(employee_list)
print 'The number of employees you have entered: ', list_size
for index in range(list_size):
print employee_list[index],
Related
I'm a little new to Python so I apologise in advance if this is a really simple question but I have been trying to wrap my mind around this problem for a while now.
Simply put, my code is to prompt the user if they have written down a couple of values correctly, If they have I want the loop to continue so the values can be saved to a database. If they have not I would like the code to loop back to the top of the while loop so they can re-enter the values.
For some reason when I enter 'no' It goes through the loop regardless, how may I fix this?
Here's the code below:
while True:
clear()
print("\nPlease input the required data.\n")
in_name = input('Name: ')
in_email = input('Email: ')
in_address = input('Address: ')
clear()
print("\nDoes this look correct?\n")
print("#--START--#\n")
print("Name: " + in_name)
print("Email: " + in_email)
print("Address " + in_address)
print("\n#---END---#\n")
validate == input(">>> ")
if validate == "no":
continue
elif validate == "yes":
print("/nAttempting to copy to the database...")
cursor.execute("""
INSERT INTO contacts(name, email, address)
VALUES (?,?,?)
""", (in_name, in_email, in_address))
conn.commit ()
print ( 'Data entered successfully.\n' )
break
(I should note that this write program is part of a larger program, the loop is nested within another loop that acts as the main menu, perhaps that may help.)
the keyword continue will take you back to the next iteration without finishing the current one, example.
for i in range(5):
if i == 2:
continue
print(i * 5)
This means that when i is 2 it wont print(i=2 * 5), instead it will go up to start the next loop where i=3. The output will be
0
5
15
20
If you use break, it will just completely stop and exit out of the iteration once it reaches this keyword.
I think you're looking for the keyword pass.
'while True:' will always be True, meaning the loop will go on forever. I believe that you'll need to break out of the loop for it to stop. Based on Jorge Alvarez's answer, even changing 'continue' to 'pass' will allow the loop to go forever.
If I understand correctly, you'll need to change the initial 'while True:' statement to test whether validate equals 'no' or 'yes'.
I have a while statement which works well and I have a whole section of code that asks the user to input how many names they have which will then ask them for a name that amount of times and then each time a name will be entered.
I need the section of the names entered to be error tapped but I don't know how to do it, as I have a while statement and I may need to put another while statement in, although I have error tapped the section for amount of names in numbers.
Also there is code further on with a dictionary and sorts but I need help with the one section of error tapping started at while currentnum part
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
Yep. The easiest way to describe what you're doing is to use the .isalpha attribute in an if statement. First you will have to def your while loop
Like the following:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
Baisically you have to define the loop and then run it. The if statement(which is the part you should add to your loop) then checks if there is nothing other than letters. If true, your done with error trapping and the loop is exited. The program continues outside the loop. If not then the while is repeated because the Loop() function is called again.
Your code looks very good to me. I dont see what input can the user put that could cause an error, since most data in python can be stringed AND names can be pretty much anything!. If you could comment exactly what error could be caused i might be able to help you
def erVal():
print("The value entered is not vaild, enter a valid value")
name = input("Enter your name ")
while True:
erVal()
if name.isalpha() is True:
break
does not loop back WHY??
i am trying to display the error message when the user leave the name input blank
the while loop works but it keeps running printing the errVal
To answer your question. Assuming the formatting is correct this code will enter an endless loop if a non alpha value is entered. It will not return to ask for the name again. Entering an alpha value for name will cause the break to be executed which will end the while loop.
I assume you meant something more like the following:
def erVal():
print("The value entered is not valid, enter a valid value.")
while True:
name = input("Enter your name ")
if name.isalpha() is True:
break # will exit the while if name is alpha
else:
erVal()
Python is very interactive, in the future I suggest you test smaller pieces of the code such as playing with the while loop to see what break does. This will improve your understanding of the code.
I have a problem with this dice game. When I try to make it skip to the next piece of code, it just goes back. Please help:
import random # Importing the module
decision = ('y') # Setting variable 'decision' as y
roll_number = 1 # Setting variable 'rolling_number' as 1
name = input('What is your name?\n') # Setting a variable as a condition so that the User can change the variable. It is an input.
while decision == ('y'): # While loop for the decision
if roll_number > 1: # If loop for roll_number
same_person = input('\nAre you the same person? If so please press y, if not please press n. Pressing anything else ask your name again!\n') #Asking if the User is the same person
if same_person == ('y'): # If it is the same person
print('Okay!') # Outputs 'Okay!'
continue # Skips to the next part of the code
else: # Otherwise
name = input('\nWhat is your name?\n')#Asks name again
number = random.randint(1,6) # Generates random number between 1 and 6
ready = input('\nPress any button to roll the die!\n') # Lets the user know when it's ready
print('Rolling...\n'*4) # Output Rolling... 4 times
print(name,'! Your die shows a ',number,'!\n') # Outputs the name and the number
roll_number = roll_number+1 # Adds 1 to the variable 'roll_number'
decision = input('Do you want to try again? If so please press y, if not please press n. Pressing anything else will stop the program!\n') # Letting the User change the variable so they can use the program
else: # Otherwise
print('Bye!') # Outputs 'Bye!'
Thank You!
continue only skips the rest of the body of the loop, it does not exit the loop. As such, when same_person == 'y' is true, you send Python back up to while decision == 'y' (note, the parenthesis around 'y' are entirely redundant here and can be omitted).
Use break to exit the loop. The else statement at the end of the loop will then not be executed, you may want to remove else: there and un-indent the print('Bye!') line.
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.