Python jumping a while Loop - python

I'm, trying to avoid this while loop what is wrong
while True:
start = input("Ok, are you ready now?\n")
if (start != "yes" and start != "no"):
print ("Please enter Yes or No")
else:
break
elif start =="no":
continue

Your indentation is totally wrong. Your code is not valid.
By the way, there's the correct indented code:
while True:
start = input("Ok, are you ready now?")
if start == "yes":
break
elif start == "no":
continue
else:
print ("Please enter yes or no.\n")
Note that it works in Python3

I can't edit the question to fix your indentation
but i would guess that you mean why it is not working.
you cannot have elif after else for the same if
the correct flow is
if
elif
else
so it should be
while True:
start = input("Ok, are you ready now?\n")
if (start != "yes" and start != "no"):
print ("Please enter Yes or No")
elif start =="no":
continue
else:
break

Related

The same message appears when I type `yes` in the loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
When I enter yes to repeat the game, then instead of repeating, this message appears:
do you want to play again (yes or no):
This only happens when I enter yes. But if I enter no, then it exits from the game.
Code I have
print(' Welcome to the gussing game :)')
print("\n\nyou have only 3 attempts to win ")
hidden_word = 'zak'
guess_word = ''
count_attempts = 0
limit_attempts = 3
play_again = 'yes'
while play_again == 'yes':
while (guess_word != hidden_word) and (count_attempts < limit_attempts):
guess_word = input("\nplease enter your word: ")
count_attempts += 1
if count_attempts == limit_attempts and guess_word != hidden_word:
print("Sorry, you lose due to Out of attempts ")
elif guess_word != hidden_word:
print("Wrong attempt, try again ...")
#Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }
else:
print(" Wow you won !!")
play_again = input('\ndo you want to play again (yes or no): ').lower()
Question
This is because you didn't reset the value of your variable, guess_word and count_attempts. Therefore, while (guess_word != hidden_word) and (count_attempts < limit_attempts): is always false in your second iteration onwards, and the inner while loop is skipped.
You can reset the value before the inner while loop.
while play_again == 'yes':
guess_word = ''
count_attempts = 0
while (guess_word != hidden_word) and (count_attempts < limit_attempts):
guess_word = input("\nplease enter your word: ")
count_attempts += 1
if count_attempts == limit_attempts and guess_word != hidden_word:
print("Sorry, you lose due to Out of attempts ")
elif guess_word != hidden_word:
print("Wrong attempt, try again ...")
#Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }
else:
print(" Wow you won !!")
play_again = input('\ndo you want to play again (yes or no): ').lower()
The problem you're having is that after the user enters "yes", you need to set guess_word back to an empty string and reset count_attempts, otherwise the inner while loop conditional check is already false. In a final implementation you would also reset the hidden word at this time as well.
The simplest solution would be to move almost all of the setup code inside of the outer while loop
limit_attempts = 3
play_again = 'yes'
while play_again == 'yes':
print(' Welcome to the gussing game :)')
print("\n\nyou have only 3 attempts to win ")
hidden_word = 'zak'
guess_word = ''
count_attempts = 0
while (guess_word != hidden_word) and (count_attempts < limit_attempts):
guess_word = input("\nplease enter your word: ")
count_attempts += 1
if count_attempts == limit_attempts and guess_word != hidden_word:
print("Sorry, you lose due to Out of attempts ")
elif guess_word != hidden_word:
print("Wrong attempt, try again ...")
#Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }
else:
print(" Wow you won !!")
play_again = input('\ndo you want to play again (yes or no): ').lower()

How to make the code jump back instead of forward?

I was working with a mastermind assignment but one of my define function isn't working as expected.
How do I make the "quit" jump back to "have a guess..." instead of continue to the colourlst?
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit.lower() == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit.lower() == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
Just add else: and indent what's below it right before colourslist. Python codes do not "jump back":
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit[0].lower()[0] == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit[0].lower()[0] == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
else:
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
BONUS: I added [0] at the values of dc_quit to force taking one character only. A full 'yes' or 'no' works too ;-)

While loop stopping even if it's False?

I thought the logic of my while loop made sense, but it abruptly stops after the first loop.
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
valid = False
while valid == False:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
return choice
if choice ==1:
valid=True
display_modules_average_scores()
menu()
elif choice ==2:
valid=True
display_modules_top_scorer()
menu()
elif choice==0:
exist=True
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
If I enter 5, it does:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
But if I enter 5 again, it stops the program. What am I doing wrong?
if I enter 5 again, it stops the program
Because you have a return statement that immediate ends the function you're running within.
You seem to be trying to create an infinite loop. You can start with testing exit and invalid conditions with this. Note:choice will never equal an empty string
while True:
choice=int(input("Enter choice (0 to exit):"))
if choice == 1:
pass # do something
elif choice == 2:
pass # do something else
elif choice == 0:
break
else:
print("Invalid choice, please enter again")
print("Thanks")
To exit the loop, you can use break, which executes code after the loop. Use return to end the function, as mentioned. There is a difference
If you're running this loop inside of the menu() function, you do not need to actually call the menu function again. That's the point of the while loop
By defining the function we can perform this task easily with no code duplication.
The Below code calls the function inputchoice() and then the inputchoice() will check the value entered by the user and if there the value is not valid then the inputchoice will call itself and the process continues untill the user enter correct input.
def inputchoice():
choice=int(input("Enter choice: "))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice!")
choice = inputchoice()
return choice
def menu():
choice = inputchoice()
print(choice)
if choice ==1:
valid=True
print("Do something if Valid = True")
elif choice ==2:
valid=True
print("Do something if Valid = True")
elif choice==0:
valid=True
print("Do something if Valid = True")
menu() #implementing menu function
I prefer making a dictionary with your functions, keeps the code clean in my eyes.
Consider this code here:
def choice1():
return 'choice1'
def choice2():
return 'choice2'
def defaultchoice():
return 'default'
choicedict = {
'1': choice1,
'2': choice2
}
while True:
choice = input("Enter choice (0 to exit):") # maintain as str to avoid error!
if choice == '0':
break
value = choicedict.get(choice, defaultchoice)()
print(value)
Single Function Code
def menu():
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice, please enter again")
menu()
elif choice ==1:
print("Oh, its working")
menu()
elif choice ==2:
print("Oh, its working")
menu()
elif choice==0:
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
menu()
Hi i would use a while loop like this. It would seem from this assignment that we are from the same institution. This is what i use for my code, I hope this helps.
while True:
user_input = input("Enter choice: ")
if (user_input == "0"):
print("=====================================================")
print("Thank You for using Students' Result System")
print("=====================================================")
break
elif(user_input == "1"):
display_modules_average_scores()
elif(user_input == "2"):
display_modules_top_scorer()
else:
print("Invalid choice, please enter again")

How do I fully break out of a while loop nested inside a while loop? [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
How can I fix the if statements in my while loops?
(1 answer)
Closed 5 years ago.
I am wondering if someone can help me figure out how to fully break out of my while loop(s) and continue with the rest of my program. Thanks!
import time
while True:
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
break
#Continue with rest of my program
The solution below adds a flag to control when to break out of the external loop that is set to break out each loop, and set back if no break has occurred in the internal loop, i.e. the else statement has been reached on the inner loop.
import time
no_break_flag = True
while no_break_flag:
no_break_flag = False
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
no_break_flag = True
#Continue with rest of my program
Obviously as you have a condition of while True on the inner loop you will always exit by breaking, but if you had some other condition this would break the external loop only if a break statement was reached on the inner loop.

How to exit only an 'if' block in Python and not the entire program

Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".
In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.
import random
import sys
loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
print('Thank you!! Visit again.')
sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')
lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)
while loop == 'yes':
user_input1 = int(input('Please enter the first number: '))
user_input2 = int(input('Please enter the second number: '))
user_input3 = int(input('Please enter the third number: '))
print('Your numbers are: ', user_input1, user_input2, user_input3)
def check():
if lotto_numbers != [user_input1, user_input2, user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1, user_input2, fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result = check()
if (result == True):
print("Congratulations!! You won!!")
else:
print("Oops!! You lost.")
if (fireball == 'yes'):
fb_result = fbcheck()
if (fb_result == True):
print("Congratulations, you won a fireball!!")
else:
print("Sorry, you lost the fireball.")
print('No of retries remaining: ', (3 - retry))
if (retry == 3):
sys.exit()
loop = input('Do you want to try again? yes/no: ')
continue
else:
pass
print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.
I.e.:
if some_condition:
# Do stuff
# Stop indent and do some more stuff
I think I gotcha your willing.
You want to execute something after the if condition is executed? So, create a subtask, and call it!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()

Categories