My loop continuously outputs without stopping [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I am trying to make this code break when the user enters "X" and allow it to continue when the user presses enter.
With what I have here, it stop and waits for enter input to output the next name I want it to output but doesn't break when I input X.
def Main():
userSent = input("Enter X to quit ").upper()`
while True:
if userSent == "X":`
break
else:
print(GenName())
input()
I tried getting rid of the input to fix the problem but then it just continuously went on nonstop. I expected it to break on X or else print GenName() and stop to wait for input.

The problem is that you only define userSent once, right before the loop starts. That means that if the first thing you enter isnt a capital X, then the program will never end. Try doing this:
def Main():
while True:
userSent = input("Enter X to quit ").upper()
if userSent == "X":
break
else:
print(GenName())

Within your loop, userSent is never updated. If the loop enters, it will never exit.
I suspect your last line is meant to be something like userSent = input().

You assign userSent value but you never updated it inside the while loop. You can use either of these versions:
def Main():
userSent = input("Enter X to quit ").upper()
while userSent != "X":
print(GenName())
userSent = input().upper()
def Main():
userSent = input("Enter X to quit ")
while userSent != "X" and userSent != "x":
print(GenName())
userSent = input()

Related

Python count program wont work as expected [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
im new to python and i have a count program that i dont know whats wrong with, for some reason, when trying to run it, when i put in Y or N for slow count, it just does nothing and exits with code 0.
Heres my code:
def cnt(start, end):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("Done!")
def count():
num = int(input("Enter a number to count to: "))
#Slow count meaning counting 1 by 1 in console.
slcnt = bool(input("Would you like to slow count? Y/N: "))
if slcnt == "Y":
cnt(0, num)
elif slcnt == "N":
for i in range(num):
print(i)
print("Done")
count()
The problem is this line slcnt = bool(input("Would you like to slow count? Y/N: ")), you can't make it boolean because you are asking for a character. It may be fixed like this:
import time
def cnt(start, end):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("Done!")
def count():
num = int(input("Enter a number to count to: "))
#Slow count meaning counting 1 by 1 in console.
slcnt = input("Would you like to slow count? Y/N: ").upper()
if slcnt == "Y":
cnt(0, num)
elif slcnt == "N":
for i in range(num):
print(i)
print("Done")
count()
You didn't add the line import time, but I guess it was a mistake when you pasted the code.
I also added upper() to the input function, so the script will accept Y/N and y/n.

multiple choice quiz , how to deal with unwanted answer? | python

So, i have been learning from a video on youtube about basic multiple choice quiz with few possilble answers like a, b, c.
but, if the user enters r or 44 the code just wont count it as a right answer.
I want the code to print the user the question again. Ive tried to write something but now it is moving on to the next question only if the user enters the right question.
def test_run2(questions):
score = 0
for question in questions:
while True:
user_answer = input(question.prompt)
user_answer.lower()
if user_answer == "a" or "b" or "c":
if user_answer == question.answer:
score = score + 1
break
# For each of your questions
running = True
while running:
print("") # Put question in here
if answer in possibleAnswers:
# Check if correct or wrong, etc.
running = False
else:
print("Please provide a valid answer")
# Repeat again for next question
Note that this is just a snippet, you need to add the other sections of your code to it where applicable.

(Python) Trouble making the user input promt another quiz question or break the loop

I'm pretty new to programming, so please pardon me!
***EDIT 2: Ok so this is the full thing. Everything is working fine except when I try to break out of the while enthusiasm is True: loop, I just keep getting more and more questions (the loop keeps running)
I'm building a Python trivia quiz, and I managed all the answer input loop to work (doesn't allow invalid input, breaks the loop succesfully)
I want the program to ask the user "Would you like another question? (y/n)" and stop the program if 'n'.
The problem is no matter what I tried, I keep getting more trivia questions!
Thanks in advance
import requests
import pprint
import json
import html
print("Welcome to the ultimate test of knowledge and valour, The Internet Quiz!")
print("You will be given an array of multiple choice questions in general knowledge")
input("Press Enter to start!")
y_n = ["y", "n"]
import random
q_num = 1
score = 0
enthusiasm = True
while enthusiasm is True:
r = requests.get("https://opentdb.com/api.php?amount=1&category=9&type=multiple")
question = json.loads(r.text)
first = question['results'][0]['correct_answer']
second = question['results'][0]['incorrect_answers'][0]
third = question['results'][0]['incorrect_answers'][1]
fourth = question['results'][0]['incorrect_answers'][2]
print("--------------------------------------------------------")
print("Question number " + str(q_num)+ ":")
print(html.unescape(question['results'][0]['question']))
options = [first,second,third,fourth]
random.shuffle(options)
for X in options:
print(html.unescape(X))
legend = (
(options[0], 1),
(options[1], 2),
(options[2], 3),
(options[3], 4)
)
error = False
while error is False:
guess = input("Please enter the number of your answer(1-4):")
try:
guess = int(guess)
except:
print("Your answer must be a number between 1-4.")
continue
if guess <1 or guess > 4:
print("Your answer must be a number between 1-4.")
continue
else:
error = True
if (first, guess) in legend:
score += 1
q_num += 1
print("Correct! \nCurrent score: " +str(score))
acid = True
while acid is True:
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
print("Invalid input. Please enter y/n.")
continue
elif yesno.lower() == "y":
break
else:
acid=False
error=True
continue
else:
print("Incorrect! Better hit the books, buddy! \nCurrent score: " +str(score))
q_num += 1
acid = True
while acid is True:
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
print("Invalid input. Please enter y/n.")
continue
elif yesno.lower() == "y":
break
else:
acid=False
error=True
continue
You have two while loops:
while enthusiasm is True:
and
while error is False
Let's look at what happens when you ask if the user wants another question (simplified a little):
yesno=input("Would you like another question? (y/n)")
if yesno.lower() == "y":
break
else:
error=True
You set error to True, but you do not set enthusiasm to False, so the loop starts again at the top. Looking further, enthusiasm never gets set to False, so that condition will always start over. Simply writing
else:
error = True
enthusiasm = False
would be fine. I also would recommend thinking about if you want two loops, and what the purpose of the enthusiasm variable is.
There's a lot of other refactoring that can be done here, but not that you probably should write
while not error:
instead of explicitely checking if error "is" False. Similarly,
while enthusiasm:
is a good check on a boolean
Similarly,
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
can be improved. You don't need to cast yesno to a string, becuase that's what happens when it comes from input. You don't need the try/except either (you may have taken this from an int cast, elsewhere). Since you've already converted yesno to lower once, you don't need to keep doing that every time you compare it to a y or n.
Possible to stop the program with:
import sys
sys.exit()

Python dice rolling game stuck on code, want to loop to restart if certain user input is met [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I'm fairly new to this whole coding scene and I'm doing some beginner projects to build upon what I've learned.
Essentially what I'm trying to do is get the program to restart back at the top of the loop if the user wants to roll again, or accidently types something else that is not "yes" or "no".
In addition, is there a way to skip a certain line of code, so that way the user isn't asked if they want to roll twice?
Should I be using functions instead?
Couldn't find any info that helped me directly so thought I would ask, any info at all would be helpful, thanks!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(Original code as image)
You've asked a couple of questions in one, but I'll try and answer them with an example. First off, to have an infinite running while loop, you can just set it to True (basically the same as your 1=1 statement, just easier).
Your second question regarding functions is typically yes - if some code needs to be repeated multiple times, it's usually good to extract it to a function.
Your third question regarding skipping a line of code - easiest way to do this is if/else statements, like you've already done. One thing that can be improved, is by using continue; it restarts the loop from the beginning, whereas break breaks out of the loop.
Here's a simple code example for your scenario:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
Hey I would do it like this
import random
useless_variable = 1
lets_play = input("Do you want to roll. yes or no: ")
if lets_play.lower() == "yes":
while useless_variable == 1:
useless_variable == 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("You got a: ", d1, "from the first dice")
print("You got a: ", d2, "from the seond dice")
ask = input("Wanna roll again(yes or no):")
if ask.lower() == "yes":
useless_variable = 1
else:
break
If you want to do an infinite loop then while True: Otherwise you can put in your while something like while condition == true and in your answer when is "no" change the condition to false.
I would do it like this
def roll():
if(lets_play.lower() == "yes"):
//Code here
elif lets_play.lower() == "no":
//Code here
else:
print("invalid")
while True:
lets_play = input("Roll?")
if lets_play.lower() == "exit":
break
else:
roll()

Exiting Program properly using two while loops? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to programming and I'm trying to make an option for the user to exit upon "yes" or y ,or "no" or "n", but I am having the worst luck in trying to do this. Could someone help me point out my error and hint at a better way to do this? I would really appreciate the assistance. Thank you.
Edit
I apologize about my vague posting. Let me be a little more clear in my question. Using two while loops to execute my program in a loop, I want to give the user a choice to whether they want to leave or redo the program. The program, however, doesn't exit properly, even though I've stated that "n" specifically is set to terminate the program. The code will, however, will loop back when I request or don't request to redo the main program, whether I enter "y" or "n".
I am confused as to what exactly is wrong with my loop, as it should close when I enter "n". What exactly is the problem with my loop's exit?
My coding
while True:
# Blah Blah Blah. Main program inserted here.
while True:
replay = input("Do another Calculation? (y/n)").lower()
if replay in ('y','n'):
break
print("Invalid input.")
if replay == 'y':
continue
else:
print("Good bye")
exit()
Your .lower should be .lower(). .lower() is a function, and calling it without parentheses doesn't do anything:
>>> string = 'No'
>>> string.lower
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower
>>> x
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower()
>>> x
'no'
>>>
Also, you are checking for equality in replay == input(...). You just want a single = to assign:
>>> result = 0
>>> result == 4
False
>>> result = 4
>>> result == 4
True
>>>
You also have an unwanted : after print replay in your second while True loop.
This is a suggestion: instead of using replay in ("no, "n"), which is very unpythonic, use the built-in method startswith(char) to see if it starts with that character:
>>> string = "NO"
>>> string.lower().startswith("n")
True
>>> string = "yeS"
>>> string.lower().startswith("y")
True
>>>
This also works for input like naw, or yeah, etc.
Here is your edited code:
a = int(input("Enter the first number :"))
b = int(input("Enter the second number :"))
print("sum ---" + str(a+b))
print("difference ---" + str(a-b))
print("product ---" + str(a*b))
print("division ---" + str(a/b))
input()
while True:
print("Do you want to try again?")
while True:
replay = input("Do another Calculation? 'y' for yes. 'n' for no.").lower()
print(replay)
if replay.startswith('y') == True:
break
if replay.startswith('n') == True:
exit()
else:
print("I don't understand what you wrote. Please put in a better answer, such as 'Yes' or 'No'")
I see some syntax errors:
1) print replay should be print(replay)
2)if replay in ("yes","y") should be if replay in ("yes","y"):
3)if replay in ("no","n") should be if replay in ("no","n"):

Categories