I need some help understanding the differences between the following. In the first example, I want the loop to break when the user inputs False:
true = True
while true:
print("Not broken")
true = input("to break loop enter 'False' ")
There was a question asked at:
how do I break infinite while loop with user input
Which gives this solution:
true= True
while true:
print("Not broken")
true = input("to break loop enter 'n' ")
if true == "n":
break
else:
continue
And I don't understand why the first method doesn't work and the second does??? Why doesn't python take the input as if someone was changing the script and change the variable "true"? Whats going on behind the scenes?
Any help would be appreciated. Thanks in advance :)
The while statement is conditional, and the user entering the String "False" will still resolve to a True outcome.
For an idea of what Python considers True and False, checkout this link: https://realpython.com/python-conditional-statements/
Building on this answer Converting from a string to boolean in Python?, the best way to check is:
true = True
while true is not 'False':
print("Not broken")
true = input("to break loop enter 'False' ")
Related
I've got a simple piece of code that asks for user input and returns a boolean variable. In case the input was unacceptable, the user has the chance to correct herself. But the boolean gets properly updated only when the else part of the if-statement is not invoked. When it is, the function always returns False.
def tryAgain():
bol = False
print('Do you want to try again? (Y/N)')
answer = input('> ').lower()
if (answer == 'y' or answer == 'n'):
if answer == 'y':
bol = True
else:
print('Your answer could not be parsed')
tryAgain()
return bol
That line of
tryAgain()
should be
bol = tryAgain()
And it will work. :-)
Oops... as per what Saeed said... Hadnt read his comment before replying.
I'm making a guessing game or computer science in school where the number to guess is seven. I have tried using while loops and if elif else statements but it doesn't seem to want to make a conditional loop My code is as follows:
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
else:
print("Well done")
Any help would be appreciated thanks. I need it in about a week and a half's time.
If you're trying to allow your player to continuously guess the input needs to be at the top of the while loop, before the conditional-branch
while(True):
guess = input("Make a guess: ")
if(guess == 7):
print(guess,"was correct!")
break
else:
print("Nope. Guess again.")
Of course, you could make it more interesting in a variety of ways.
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
guess=int(input("Guess a number!"))
else:
print("Well done")
var=0 #set var to 0, to exit the loop
Try this. You need to exit the loop, and to do that, var needs to be set to 0.
How do you reset a while True loop. For example this is my code:
x=True
while x==True:
print ("Random Text")
randomtext= input()
if randomtext == "yes":
print ("hi")
x=False
elif randomtext == "no":
print("This is supposed to reset the loop")
#resets loop and prints Random Text again
print ("hi")
if x==True:
print ("placeholder text")
input()
I want it to reset the loop if "randomtext" is equal to yes. I want to reset it it in the middle of the loop. This is a very simple question but this is getting in my programming. Thank you.
I'm assuming that by resetting the loop you mean jumping code until reaching the start of the loop again. This is done with the "continue" keyword.
if randomtext == "yes":
continue
If you actually meant breaking out of the loop, you should instead use the "break" keyword.
from random import randint
isRunning =True
while isRunning:
dice1 = randint(1,7)
dice2 = randint(1,7)
print("The first die landed on ℅d and the second landed on ℅d." ℅ (dice1,dice2))
user_input = input("Contiue? Yes or No?\n>")
if user_input == "Yes" or "yes":
print("="*16)
elif user_input == "No" or "no":
isRunning = False
I feel like I'm making such a simple mistake and when I decided to look into global variables and what not it still doesn't help. Could anyone explain why the while loop doesn't terminate, although the variable was set to false.
if user_input== "Yes" or "yes" should be
if user_input== "Yes" or user_input =="yes", alternatively it's equivalent to if any(user_input==keyword for keyword in["Yes", "yes"]):
your original if clause is splitting to
if user_input=="Yes" or if "yes" and if "yes" always true, therefore your if-elseif clause always go to if clause.
I'm trying to write a MasterMind game using classes and objects and I'm currently stuck around some of my loops.
while True:
# create a combination
# test the combination
while game_won == False:
print(scoreboard)
# player input combination
# combination is tested then added to scoreboard
tries_left = tries_left+1
if game_won == True:
print(You Won!)
input = Play Again? Y/N
if tries_left == 10:
print(You Lost!)
input = Play Again? Y/N
How do I do to go back to my while True -> create combination from my last if statement? (if tries_left == 10:)
What's wrong
Your first while True doesn't have anything in it, You need to indent code under it if you want it to be inside the loop.
There is a few typos, missing comment characters, and quotation marks.
What needs to happen
When the nested while loop while game_won == True exits, the code will return looping the parent loop while True, which will replay the game, if the user wishes.
Your code fixed (with a few improvements)
Following is how you can loop the game forever (given the user wishes it).
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""
# loop the entire game while the user wishes to play
while user_wants_to_play:
# Create the combination
# Test the combination
# Game isn't done when started
game_done = False
tries_left = 10 # Arbitrary number I chose
while not game_done:
# Play the game
print("Scoreboard")
# Subtract one to tries left
tries_left -= 1
if game_done:
print("You won!")
elif tries_left == 0:
print("You lost!")
game_done = True
# if users answer was 'n'
ans = input("Play again? Y/N \n")
if ans.strip().upper() == 'N':
user_wants_to_play = False
Improvements
Boolean logic is more pythonic using not instead of myBool == False
while True: changed to while user_wants_to_play:
User input is scrubbed to ignore white-space and lower case
Changed game_won to game_done
Made tries_left count down instead