I have a python3 program that guesses the last name of an individual based on the input of the user. But I figured out how to break if the user answer now, but when the user says yes it just re-enter the loop again with the same initial question.
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'no':
print("Great")
else:
time.sleep(2)
exit('Shame, thank you for playing')
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
DEMO - If the user answer 'yes'
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
etc.
So basically I want the program to exit on no, but continue on yes with the next question which is "Please tell me the first letter in your surname?"
Any idea?
I through after picking up some suggestion here, that I could use a while loop, but as the question stands, I did not get it right.
Please answer in a not so technical way, as my knowledge of python is very limited, still trying to learn.
I misunderstood the problem at first. You actually need to break the while loop when the user says Yes, so you can proceed to the 2nd question. And using an exit is fine when he says No, just remember that it will exit the whole program, so if you want to do something else after he says no, it might be better to use return and put them into functions.
Your code should be more or less like this:
import time
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
break # This will break the actual loop, so it can pass to next one.
elif answer.lower() == 'no':
# I recommend printing before so if it's running on a terminal
# it doesn't close instantly.
print('Shame, thank you for playing')
time.sleep(2)
exit()
# I suggest adding this else because users don't always write what we ask :P
else:
print('ERROR: Please insert a valid command.')
pass # this will make it loop again, until he gives a valid answer.
while True:
# code of your next question :P repeat proccess.
Feel free to ask any question you have about the code :)
As CoryKramer in the comments pointed out, use break instead of exit. Exit is a python function that exits the process as a whole and thus it shuts down the interpreter itself.
Break will close the closest loop it belongs to. Thus if you have two while loops, one written inside the other. A break will only close the inner while loop.
In general your code will go something like this
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
else:
time.sleep(2)
print("Thank you for playing!")
break
This will keep looping as long as the user keeps entering yes.
if you want to you an infinite while loop you need to control your loop state. Also i created a SurnameFunc. Using seperate functions is more readable for big projects.
def SurnameFunc():
return "Test Surname ..."
State= 0
lastname_tip = ""
while(True):
if(State== 0):
answer = input('Do you want me to guess your name? yes/no :')
if(answer == 'no') :
print ("You pressed No ! - Terminating Program ...")
break
else:
State = 1
elif(State == 1):
lastname_tip = input('Please tell me the first letter in your surname?').lower()
State = 2
elif(State == 2):
print ("Your Surname is ..." + SurnameFunc())
State = 0
print ("Program Terminated !")
Related
Here is the code:
# Write a program that asks the user how many people
# are in their dinner group. If the answer is more than eight, print a message saying
# they’ll have to wait for a table. Otherwise, report that their table is ready.
people = input("How many people will you be having in your dinner group? ")
people = int(people)
if people > 8:
print(input("We'll have to put you on a short wait, is that okay?" ))
if 'yes':
print("Okay, we will call your table in the next 15 minutes.")
else:
print("Okay, we will see you another night, then. Thank you for stopping by.")
else:
print("Perfect! Right this way; follow me.")
I'm not sure if my 2nd "if" statement is correct, because I want to make it so that if someone says "yes" and anything else in their sentence, or "yes" later in their sentence, then it will print that ("Okay, we will call your table in the next 15 minutes.") print statement.
Currently, if I type anything,(after answering the first question with any number above 8) even "no" it will still print the ("Okay, we will call your table in the next 15 minutes.") statement. I'd like the same thing for the "yes" explained above to happen for the "no" answer as well.
I tried putting 'yes' after the if, but I feel like I am missing something. Same for the 'else'.
You have to store the result of your input in a variable:
choice = input("We'll have to put you on a short wait, is that okay?" )
if choice == 'yes':
# Do something
else:
# Do something else
You aren't saving the value of the response to be able to check it in your second if:
if people > 8:
response = input("We'll have to put you on a short wait, is that okay?")
if response == 'yes':
print("Okay, we will call your table in the next 15 minutes.")
else:
print("Okay, we will see you another night, then. Thank you for stopping by.")
else:
print("Perfect! Right this way; follow me.")
im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)
I hope to accept user's input as yes/no, if user input yes, the code will continue run the avaliable code, it user input no, the code will notifying user again and code will not run until user input 'yes' finally
Here is the brief introdcution:
# Here is part1 of code
a = input('Have you finished operation?(Y/N)')
if a.lower() == {'yes','y' }
# user input 'y', run part2 code
if a.lower() == {'no', 'n'}
# user input no
# code should notifying user again "'Have you finished operation?(Y/N)'"
# part2 code will run until user finally input 'y'
if a.lower() !={'yes','y', 'no', 'n'}:
# user input other words
# code should notifying user again "'Have you finished operation?(Y/N)'"
# here is part2 of code
Do you have any ideas on how to solve this problem, I would appreciate if you can provide some suggestions
Update
here is the code I'm tring
yes = {'yes','y',}
no = {'no','n'}
print(1)
print(2)
while True:
a = input('Have you create ''manually_selected_stopwords.txt'' ???(Y/N)''')
if a.lower().split() == yes:
break
if a.lower().split() == no:
continue
print(3)
print(4)
When I run it, it shows as follows, the first time I tried input 'n' and then 'y', this will always notifying me, even I type into 'y' and will not print 3 and 4
1
2
Have you create manually_selected_stopwords.txt ???(Y/N)>? n
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)>? y
Have you create manually_selected_stopwords.txt ???(Y/N)
Some of your tests are unnecessary. You have the same outcome if you type "no" as typing "marmalade".
# Here is part1 of code
while True:
# Calling `.lower()` here so we don't keep calling it
a = input('Have you finished operation?(Y/N)').lower()
if a == 'yes' or a == 'y':
# user input 'y', run part2 code
break
# here is part2 of code
print('part 2')
EDIT:
If you want to use a set rather than or then you can do something like this:
if a in {'yes', 'y'}:
You are comparing the result of input() (a string) with a set of strings for equality. They are never equal.
You can use in to check if your input is in the set:
Linked dupe asking-the-user-for-input-until-they-give-a-valid-response applied to your problem:
# do part one
yes = {"y","yes"}
no = {"n","no"}
print("Doing part 1")
while True:
try:
done = input("Done yet? [yes/no]")
except EOFError:
print("Sorry, I didn't understand that.")
continue
if done.strip().lower() in yes:
break # leave while
elif done.strip().lower() in no:
# do part one again
print("Doing part 1")
pass
else:
# neither yes nor no, back to question
print("Sorry, I didn't understand that.")
print("Doing part 2")
Output:
Doing part 1
Done yet? [yes/no] # adsgfsa
Sorry, I did not understand that.
Done yet? [yes/no] # sdgsdfg
Sorry, I did not understand that.
Done yet? [yes/no] # 23452345
Sorry, I did not understand that.
Done yet? [yes/no] # sdfgdsfg
Sorry, I did not understand that.
Done yet? [yes/no] # no
Doing part 1
Done yet? [yes/no] # yes
Doing part 2
I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.
I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()