I've searched the web and this site and been messing around all day, trying 100 ways to get this simple little program working. I'm practicing endless While loops and string user inputs. Can anyone explain what I'm doing wrong? Thank you!
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.islower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
your code has one thing wrong answer.islower() will return boolean values True or False but you want to convert it into lower values so correct method will be answer.lower()
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.lower() # change from islower() to lower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
You just need one amendment to this line:
Instead of
answer = answer.islower()
Change to
answer = answer.lower()
Related
I would appreciate some help with this:
I try to make a form-program of the "Then why worry" philosophy:
I wrote this code, but I can't understand how do I make the while loop repeat itself every time the user doesn't enter "yes" or "no" in both questions.
problem = str(input("Do you have a problem in life? "))
problem = problem.replace(" ", "").lower() #nevermind caps or spaces
while problem:
if problem not in ("yes","no"):
print("Please enter YES or NO")
if problem == "no":
break
if problem == "yes":
something = str(input("Do you have something to do about it? "))
something = something.replace(" ","").lower()
while something:
if something not in ("yes","no"):
print("Please enter YES or NO")
elif:
break
print("Then why worry?")
Your algorithm is linear, there is no loops in there. So, the only place you need a loop is when you try to get correct response from the user. So, I'd propose you to move that into a function and then your example turns into this:
def get_user_input(prompt):
while True:
reply = input(prompt).replace(" ", "").lower()
if reply in ['yes', 'no']:
return reply
print("Please enter YES or NO")
problem_exists = get_user_input("Do you have a problem in life? ")
if problem_exists == 'yes':
action_possible = get_user_input("Do you have something to do about it? ")
print("Then why worry?")
I'd suggest to use while True loops, so you can put the input code once, then with the correct condition and break you're ok
while True:
problem = input("Do you have a problem in life? ").lower().strip()
if problem not in ("yes", "no"):
print("Please enter YES or NO")
continue
if problem == "no":
break
while True:
something = input("Do you have something to do about it? ").lower().strip()
if something not in ("yes", "no"):
print("Please enter YES or NO")
continue
break
break
print("Then why worry?")
Using walrus operator (py>=3.8) that could be done easier
while (problem := input("Do you have a problem in life? ").lower().strip()) not in ("yes", "no"):
pass
if problem == "yes":
while (something := input("Do you have something to do about it? ").lower().strip()) not in ("yes", "no"):
pass
print("Then why worry?")
I am making a python quiz and everything is going well but there are some things that aren't working. Such as when the user has answered all the questions, I want the code to ask the user if they would like to play the quiz again. I have done the part where the code asks the user if they would like to play again but I don't know how to repeat the quiz. I have tried things such as making the quiz a variable and printing the variable but that didn't work. Please help me.
Here's the code, the part where I ask if the user wants to play again is at the bottom.
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
# this part works fine
else:
print("Thanks for playing")
time.sleep(2)
exit()
You already have an infinite loop for asking multiple questions. You can also put an infinite loop to play multiple quizes like this:
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
while True:
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
#if answer is not yes, break the outer infinite loop
if play_again != "yes":
print("Thanks for playing")
break
time.sleep(2)
exit()
You could try this, use the while True outside, then it could always run if play_again is yes and add break in the bottom if want to stop.
import random
import time
while True:
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
else:
break
# this part works fine
print("Thanks for playing")
time.sleep(2)
exit()
You can set a while loop which repeats the question until a certain condition is met. Use a variable which is true and while it is true the game continues, but once a condition is met which should end the game, switch the variable to false and the while loop should stop.
If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.
I'm looking to create a python function which would iterate through a string one element at a time based on whatever the user inputs.
So let's say the list is [hello, jello, mello]. The program will print out the string then ask the user "Do you want me to read?", then "y" it'll print the first element then loop through the string until the user inputs "n", then the loop will stop.
Thanks!
This should work:
l = ["Hello", "Jello", "Mello"]
for element in l:
while True:
answer = input("Do you want to read (y/n)")
if answer.lower() == "y" or answer.lower() == "n":
break
else:
print("Invalid input")
if answer.lower() == "y":
print(element)
elif answer.lower() == "n":
break
Hope this helps!
from collections import cycle
def print_entries_forever(list_str):
for entry in cycle(list_str):
answer = input('Do you want me to read [y/n]? ').lower()
if answer.startswith('y'):
print(entry)
elif answer.startswith('n'):
return
print_entries_forever(['Hello', 'Jello', 'Mello'])
EDIT: Loop now cycles forever until user enters 'n'.
I've been asked to make a 'Privilege Checker' and so far it is coming along pretty well. Here is my code:
def Privilige():
print("Welcome to Privilege checker V0.011")
print("Would you like to check your privileges?")
answer = input("Type 'Yes' or 'No' and hit enter ('Y', 'y', 'N', or 'n' are also valid choices).")
print("Checking priviliges.")
if answer == "yes" or answer == "Yes" or answer == "Y" or answer == 'y':
print("Privileges: Checked")
elif answer == "no" or answer == "No" or answer == 'N' or answer == 'n':
print("Privileges: Unchecked.")
else:
print("Please enter a valid option.")
Privilige()
Now, in between print("Checking privileges.") and if answer == "yes" I would like to add a progress bar that uses this character, "█" is this possible?
Any help appreciated, thanks!
You could try something like this:
from time import sleep
for i in range(60): # Change this number to make it longer or shorter.
print('█', end='')
sleep(0.1) # Change this number to make it faster or slower.