I am practicing functions. I made a short game to practice functions. I use the input() to interact.
When I enter "End" is where the confusion begins.
def endgame():
if input("Are you sure you want to exit?") == "yes" or input("Are you sure you want to exit?") == "y":
return 1
else:
return 0
The input() is triggered on both sides of the OR condition if I select anything that is not "yes".
This is not what I expected. Here is the entire code.
#function calls
def picker(v):
if v == "Game":
somegame()
elif v == "judo":
judo()
elif v == "End":
#x = endgame()
if endgame():
print("Closing")
else:
print("Restarting")
picker(input("Try to pick the secret again: "))
else:
picker(input("You must pick the secret: "))
def somegame():
print("Some game")
if input("Another game?") == "y":
picker(input("Pick another game: "))
else:
print("Game ending")
def judo():
print("Judo chop")
if input("Another game?") == "y":
picker(input("Pick another game: "))
else:
print("Game ending")
def endgame():
if input("Are you sure you want to exit?") == "yes" or input("Are you sure you want to exit?") == "y":
return 1
else:
return 0
#Start the game here
picker(input("Pick the game: "))
I can see that if it doesn't match the first OR condition, it asks for input again. I believe it should ask once and compare the input to both variables. I assume this means I would have double calls if I used other functions within a IF/OR structure in the same way?
Storing the input() in a separate variable for comparison works, but I imagine other functions that I might make that return a value having this behavior.
def endgame():
x = input("Are you sure you want to exit?")
if x == "yes" or x == "y":
return 1
else:
return 0
I know I am answering the question here, but the W3schools lesson doesnt describe this unexpected behavior.
Conditions like this in Python are evaluated from left to right, until the required condition is met or the end of the statement has been reached. Calling the same method in an or statement will result in the method being called multiple times until the condition is met, or not.
Example,
if 1 == 1 or 2 == 2 or 3 == 3 results in the rest of the condition past 1 == 1 to be totally ignored, since the whole condition has already been met. Somewhat similarly, if 1 == 2 or 2 == 3 or 3 == 3 results in the first two conditions to be evaluated. If you were to put a condition after 3 == 3, that would also be ignored assuming the previous condition (3 == 3) was True.
This sort of logic applies in conditions that incorporate and statements, though not exactly the same way depending on the circumstances of the if statement & its conditions.
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
Evening all,
I'm new to programming and I am attempting to understanding while loops that are used with if/elif/else statements.
My Thought Process
The function that I have created is a part of the game Tic Tac Toe (or Noughts and Crosses). The idea behind the function is to prompt Player 1 for their symbol choice (O or X).
My logic behind the function is such that, the player will continue to be prompted (the loop) for a valid choice. Once the player has made a valid choice, the loop should end and print the player's choice.
My Question
What I don't understand is that the function only works if I include break at the end of both the IF and ELIF blocks of code. Why won't the loop break upon the user entering a valid choice?
Please see the code, written in Python, below.
Regards,
def player_input():
player1_input = str
player1_symbol = str
while player1_symbol != "X" or "O": #loop until user supplies an valid (X or O) input
player1_input = str(input("\nPlayer 1, would you like to be X or O?: ")) #prompt user for their choice
player1_symbol = player1_input #link player1_input to player1_symbol
if player1_symbol == "X": #follow this block if Player 1 selected X
print("\nPlayer 1: You are now X") #states that Player 1 is X
print("Player 2: You are now O") #states that Player 2 is now O as a result of Player 1's choice
print("IF Statement Executed") #lets me know that this block was executed
break #WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE?
elif player1_symbol == "O": #follow this block if Player 1 selected O
print("\nPlayer 1: You are now O") #states that Player 1 is O
print("Player 2: You are now X") #states that Player 2 is now O as a result of Player 1's choice
print("ELIF Statement Executed") #lets me know that this block was executed
break #AGAIN, WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE
else:
print("\nInvalid choice. Please choose X or O.") #lets Player 1 know that he needs to make a valid (X or O) input
print("ELSE Statement Executed") #lets me know that this block was executed
The comment gives the appropriate fix. To understand why this is happening, note that the or operator combines two separate logic statements. In your case, these two logic statements are player1_symbol != "X" as well as "O". Because the latter statement is nonzero, python always evaluates it as True so that the entire statement player1_symbol != "X" or "O" is always true, no matter the value of player1_symbol.
Edit: To be clear what I mean by "the latter statement is nonzero", I mean the ASCII value for the character "O" is nonzero, so python evaluates it as true.
This question already has answers here:
How to break out of while loop in Python?
(5 answers)
Closed 3 years ago.
I am wondering:
First, is it possible to exit a
while True loop and move onto the next piece of code? This is my
while True code that I am using:
while True:
b = input("Which row of transition metals would you like to find out the melting and boiling points of? ")
print("")
if b == "1" or b == "1st" or b == "first" or b == "First":
print("First row of transition metals:")
slg(listA, a)
again = input("Continue? ")
if again == "yes":
continue
elif b == "2" or b == "2nd" or b == "second" or b == "Second":
print("Second row of transition metals:")
slg(listB, a)
again = input("Continue? ")
if again == "yes":
continue
Is it possible so that if I had if again == no, it would move on to the next piece of code, exiting the while True loop?
Use break statement to exit out of the while loop. It works with for loop as well.
The break keyword is used to exit a loop. Note that you don't need to repeat code that asks for continuation; you can write it once after your if statement.
while True:
b = input("Which row of transition metals would you like to find out the melting and boiling points of? ")
print("")
if b == "1" or b == "1st" or b == "first" or b == "First":
print("First row of transition metals:")
slg(listA, a)
elif b == "2" or b == "2nd" or b == "second" or b == "Second":
print("Second row of transition metals:")
slg(listB, a)
else:
# Without a valid response, ask again
continue
# Only ask to continue or break after a valid response
again = input("Continue? ")
if again != "yes":
break
you can also use approach like this, where you set the conditional variable true at begining then in code when the condition to set code exit come make that variable False
Below is a example code
cond = True
while cond:
// some code
if <condition>:
continue
else:
cond = False
count =1
while True:
print("Inside while loop")
for i in "python":
if i == "h":
count = 5
break
else:
print(i)
if count == 5:
break
Please have a look at the above code.
The output for the above code is -
Inside while loop
p
y
t
The above code shows that the keyword break can be used to exit from for and while loops.
The keyword continue takes it to the to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
From what you asked, if again == no, if this is provided you can exit from the while loop if you give something like this
if again == no:
break
But if you just give the below code,
if again == no:
continue
it will still be in the while loop.
Hope this helps.
I’m just starting to learn functions and I am practicing on implementing some into my code. Just a simple example... how can I code this to loop properly and break out when the user wants?
def profit(i,c):
gain = c - i
print('Your profit is:' + '' + str(gain))
def beginning():
x = float(input("What was your initial investment?"))
y = float(input("What is your investment worth now?"))
profit(x,y)
beginning()
ans = 'y'
while ans == 'y' or ans == 'Y':
ans = str(input('Would you like to calculate another investment? (Y/N)'))
beginning()
if ans != 'y' or ans != 'Y':
break
There are two ways to break out of a while loop. The first way is obviously the break statement, kind of like you have done. For it to work correctly, you need to change the condition:
if ans != 'y' or ans != 'Y':
break
This will always be true, since ans cannot be "y" and "Y" at the same time. You should change it into:
if ans not in ["y", "Y"]:
Or
if ans.upper() != "Y":
In your case however, you don't need it at all. Since in both the if statement and the while condition you are checking ans, you can get rid of the if and just rely on this.
while ans.upper() == "Y":
This will end the loop automatically when ans becomes anything other than "Y" or "y".
The only reason you would use a break here is if you wanted to exit the loop immediately, and not complete the current iteration. For example:
while ans.upper() == "Y":
ans = input("Enter selection: ")
if ans == "I want to stop right now!":
break
print("Do other things, even if ans is not Y")
In this example, "Do other things" will always be printed regardless of ans, unless ans is "I want to stop", in which case it won't get printed.
One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")