While loop stopping even if it's False? - python

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")

Related

How to break multiple loops in an if-statement within an if-statement in Python 3

How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:
while True:
print("choose 1st branch")
choice = input()
if choice == '1':
print('1, now choose second branch')
while True:
choice = input("")
if choice == "2":
print("2")
while True:
choice = input("")
if choice == "3":
print('3')#
else: #needs to ask for input for choice 3 again
print("try again")
else:print("try again")#needs to ask for input for choice 2 again
ive edited a simpler code example of what im trying to accomplish
Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.
occu = "ranger"
prompt = "-->"
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
def room1():
print("you walk into an bare room")
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = "ranger"
while True:
print("you see a door infront of you")
print("do you go left, right or forward?")
choice = get_user_choice(prompt, ("left", "right", "forward"))
if choice == "left" and hole == False:
print("\nDo you \ndodge \nor \nattack?")
choice = get_user_choice(prompt, ("dodge", "attack"))
if choice == "dodge" and occu == "ranger":
trap = True
rat = True
print("\nhole \nroom")
choice = get_user_choice(prompt, ("hole", "room"))
if choice == "hole" and rat == True:
print("you walk up to the hole, you see a faint glitter")
print("do you reach your hand in?")
print("\nyes \nno")
choice = get_user_choice(prompt, ("yes", "no"))
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
choice = True
elif choice == "no":
print(" you go back to the centre of the room")
Notice that other input also get modified to use this function to check if the choice user selected is valid or not.
The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.
proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
proceed = True # CHANGE PROCEED, NOT CHOICE
elif choice == "no":
print("You go back to the center of the room")
# Perhaps assign proceed to be True here as well?
else:
print("unknown choice, try again")
occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
print("you see a door infront of you")
print("do you go left, right or foward?")
if input(prompt) == 'left' and hole == False:
print('\nDo you \ndodge \nor \nattack?')
if input(prompt) == 'dodge' and occu == 'ranger':
trap = True
rat = True
print("\nhole \nroom")
if input(prompt) == 'hole' and rat == True:
print("you walk up to the hole, you see a faint glitter")
while True:
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice not in ['yes', 'no']:
print("unknown choice, try again")
continue # <-- Starts loop over.
elif choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
else:
print(" you go back to the centre of the room")
break # <-- Breaks out of loop.

Python: Depending on IF statement output, execute different code outside of itself

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.

When I have a function with the continue statement in it it errors out even when its only used within a while loop

all_options = ["rock", "paper", "scissors"]
outcomes = {"rockP": ["paper", "computer"], "rockS": ["scissor", "player"], "paperR": ["rock", "player"], "paperS": ["scissor", "computer"], "scissorsR": ["rock", "computer"], "scissorsP": ["paper", "player"]}
input_loop = True
def play_again():
again = input("Would you like to play again?(Yes or No): ")
if again.lower() == "yes":
continue
elif again.lower() == "no":
exit()
else:
print("Invalid input. Exiting")
exit()
while True:
while input_loop == True:
choice = input("Please input Rock, Paper, or Scissors: ")
if choice.lower() in all_options: #Making sure that the input is lowercase so it doesn't error
choice = choice.lower()
input_loop = False
break
else:
print("\n That is not a valid input \n")
computer_choice = random.choice(all_options)
if choice == computer_choice:
print("Draw!")
play_again()
computer_choice = computer_choice.upper()
current_outcome = choice + computer_choice
current_outcome_list = outcomes.get(current_outcome)
current_outcome_list.insert(0, choice)
player, winner, outcome = current_outcome_list
winning_message = print(f"{winner} has won, \nplayer chose: {player}, \ncomputer chose: {computer}.")
print(winning_message)
play_again()
How can I use that function with the continue statement? Or any other method to avoid me repeating that chunk of code. I am new to python and I need to add enough words to allow me to post this. Thank you for everybody who is going to help me :)
Error message:
C:\desktop 2\files\Python projects\rock paper scissiors\Method2>gamelooped.py
File "C:\desktop 2\files\Python projects\rock paper scissiors\Method2\gamelooped.py", line 9
continue
^
SyntaxError: 'continue' not properly in loop
It sounds like you may not be familiar with the purpose of the continue keyword. It can only be used in loops. When you reach a continue statement in a for or while loop, none of the remaining statements in the loop are executed, and the loop continues from the beginning of the next iteration (if there is another iteration to be had).
You can't continue in a function unless you're in a loop that's in a function. What is it that you intended for that continue statement to do? It might be that you just need to return.

How to execute this code without letting it become a never-ending loop?

I just tried to write the code below that takes only a whole number between 1 to 10 and prints some statements of the input value does not fulfill the required conditions.
gamelist = list(range(0,11))
def display_game(gamelist):
print('Here is your list of options:')
print(gamelist)
def user_choice():
choice = 'x'
acceptable_range = range(0,11)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input('Please enter a digit from the above options:')
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
if choice.isdigit():
if int(choice) in acceptable_range:
within_range == True
else:
within_range == False
print('The entered number is out of acceptable range!')
return int(choice)
display_game(gamelist)
user_choice()
And after running this code, even after entering the correct value it keeps on asking for the input.I am not understanding what's gone wrong exactly and where.
Arguments are generally passed to give the function access to the data is has no access to but is required to work upon the task it is assigned to do.
A good example would be if you call a function from inside other function and want to use data of local variable of your former function into latter, you would have to pass it as argument/arguments .
This is a very vague example just to give you some basic hint , basically there are many factors you would consider before deciding whether or not you need arguments in your function!!
== is for comparison, = is for assigment:
gamelist = list(range(0, 11))
def display_game(gamelist):
print("Here is your list of options:")
print(gamelist)
def user_choice():
choice = "x"
acceptable_range = range(0, 11)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a digit from the above options:")
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
if choice.isdigit():
if int(choice) in acceptable_range:
# within_range == True # this doesn't assign, but compares
within_range = True # this assigns
else:
# within_range == False # And the same here
within_range = False
print("The entered number is out of acceptable range!")
return int(choice)
display_game(gamelist)
user_choice()
This prevents the endless loop. Comparing to booleans is not really necessary. Keeping the same idea this version is a bit more readable:
def user_choice():
choice = "x"
acceptable_range = range(0, 11)
while not choice.isdigit() or not within_range:
choice = input("Please enter a digit from the above options:")
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
else:
within_range = int(choice) in acceptable_range
if not within_range:
print("The entered number is out of acceptable range!")
return int(choice)
Or even a version where choice is never a string. But maybe you haven't gotten to Exceptions yet :-). (this will change the message for '-1', though.)
def user_choice():
choice = None
acceptable_range = range(0, 11)
while choice not in acceptable_range:
try:
choice = int(input("Please enter a digit from the above options:"))
except ValueError:
print("Oops! That's not a digit. Please try again.")
if choice not in acceptable_range:
print("The entered number is out of acceptable range!")
return choice

Except block always being thrown even after going through the try block and rest of the program?

I check to see if input can be changed into an integer if it can't it starts back from the beginning of UI(). I followed it through pycharm's debugger and it will pass the try, but when I try using 4 to exit.It will go through to the end, and then go back up to the except block.
I think the parts I commented after are the only relevant parts. Thanks for any help.
def UI():
global exitBool
global newBool
if not TV.tvList:
tv = TurnOnTV()
if TV.tvList:
l = list(TV.tvList.keys())
tv = TV.tvList.get(l[0])
print("1)change channel\n2)change volume\n3)Turn on another TV\n4)Exit\n5)Choose TV") #print accepted answers
choice = input()
try:
choice = int(choice) #try block and exception block
except:
print("\nInvalid Choice\n")
UI()
choice = int(choice)
if choice == 1:
if tv:
tv.changechannel(input("enter channel: "))
else:
print('sorry no tvs are available\n')
elif choice == 2:
if tv:
tv.changevolume(input("Enter in volume: "))
else:
print('Sorry no Tvs available')
elif choice == 3:
TurnOnTV()
elif choice == 4:
exitBool = True # exit bool to exit main loop
elif choice == 5:
tv = ChooseTV(input("Enter in TV name: "))
else:
print("Invalid Choice")
if tv:
tv.display()
def Main():
while exitBool == False: #Main Loop
UI()
When you catch the error and print "invalid choice" you must not call UI() again. That way you are making a recursive call, and when the inner UI() terminates the code goes on on the outer one.
Use a "while" statement to repeat a block of code until the user makes a valid choice.

Categories