While loop not repeating once information in entered - python

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? ")

Related

Continue or quit

I am teaching myself Python. For practice I made a little mad lib game for my daughter. The problem, I want to add a "to continue press enter or type quit to exit" after line 3. I know I'm obviously doing it wrong, but I've tried conditional, flags and breaks with no luck.
#Prompt
greeting = input("Hello what is your name? ")
greeting += input(f" OK {greeting} lets wright a story together. Lets get started" )
#listing of directions
while True:
q_1 =input("please type a plural noun : ")
q_2 = input("please type an adjective: ")
q_3 =input ("please type plural noun, animal: ")
q_4 =input("Please enter an plural noun: ")
q_5 = input("Please enter an adjective: ")
q_6 = input("Please enter a color: ")
q_7 = input("Please enter an adjective: ")
q_8 = input("Please enter noun: ")
q_9 = input("Please enter plural noun: ")
q_10 =input("Please enter an adjective ")
q_11 = input("Please enter a verb: ")
q_12 = input("Please enter plural noun ")
q_13 = input("Please enter a verb-ed: ")
q_14 = input("Please enter a verb: ")
q_15 = input("Please enter noun: ")
q_16 = input("Please enter a adjective: ")
break
print("Ok here's your story")
# output with data from input
story = f"""
Unicorns aren't like other {q_1}; they're {q_2}. They look like
{q_3}, with {q_4} for feet and a {q_5} mane of hair. But Unicorns
are {q_6} and have a {q_7} {q_8} on their heads. Some {q_9} don't
believe Unicorns are {q_10} but I believe in them. I would love to
{q_11} a Unicorn faraway {q_12}. One thing I've always {q_13} about
is whether Unicorns {q_14} rainbows, or is their {q_15} {q_16}
like any other animals?
"""
print(story)
To answer your question, I've suggest something simple like this.
#Prompt
greeting = input("Hello what is your name?\n")
print(f"OK {greeting} lets wright a story together. Lets get started")
play = input('to continue press enter or type quit to exit\n')
if play == 'quit':
quit()
# Rest of your code stays the same
I'll mention also, because you said you are doing this for practice, that the way you are asking for inputs is a little bit rough.
In my example above I added a \n character. This will stop you needing to use all those spaces by putting the input response on a new line.

How to run python loop until correct input string is entered [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...

How to I repeat string inputs if the user has given a wrong answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have coded a simple game where I need the name of two players at the beginning. I want to see whether or not they have duplicate names and if they do, I want to repeat both of the inputs until they do not have duplicate names. Anyone know how to do this?
# Names
player_one = str(input("Enter P1's name")
player_two = str(input("Enter P2's name")
if player_one == player_two:
print("Please enter a different name. ")
# Code here that says 'repeat player_one and player_two'
You can do it with a function you can call again, you can even check for not allowed names etc.:
player_one = ""
player_two = ""
def getNames():
# Names
player_one = str(input("Enter P1's name")
player_two = str(input("Enter P2's name")
def checkNames():
if player_one == player_two:
print("Please enter a different name. ")
getNames()
def main():
getNames()
checkNames()
if __name__== "__main__":
main()
Output:
Enter P1's name test
Enter P2's name test
Please enter a different name.
Enter P1's name test
Enter P2's name ja
You could use while instead of if:
while player_one == player_two:
print("Please enter a different name. ")
# Code here that says 'repeat player_one and player_two'
You would then repeatedly prompt for new names until the names are different.

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.

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: ")

Categories