While loop menu never ends [duplicate] - python

This question already has answers here:
Python, unable to convert input() to int()
(3 answers)
Closed 3 years ago.
I'm trying to do a menu, it's so easy but I don't understand why never ends my loop, I attach my code:
def main():
menu_bool = False
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Why when I press "1" ask me again to choose an option? I have declared a boolean variable for stop it, menu_bool = True, but I don't know why my main function is in loop.
I try it doing a global variable but it don't works too. Then this means that my menu_bool = True is never done but I don't understand why.
menu_bool = False
def main():
global menu_bool
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Thank you so much!

As others have said, basically you are comparing strings with ints. Also I'd suggest being a bit more pythony with bools, in this case using not instead of comparing explicitly via comparison operator.
def main():
menu_bool = False
while(not menu_bool):
print("Menu:\n\t1. Copiar")
x = input()
if x == '1':
print("You have selected option 1.")
menu_bool = True

Related

How can I use conditional to control a while loop between a helper and main() function?

Directions:
Write a helper function to validate user input. Function should take inputs until valid. Invalid inputs return error message and repeat the prompt. Valid inputs return to main().
User inputs "1" to "5" each print a unique string. User input "0" exits program.
Everything should be executed from within a main() function. Only the call to main() and function definitions are global.
import sys
def getValidInput(selection):
if selection == "1":
return print("message_1")
elif selection == "2":
return print("message_2")
elif selection == "3":
return print("message_3")
elif selection == "0":
print("goodbye")
sys.exit()
else:
return print("That is not a valid option.")
def main():
askAgain = True
while askAgain == True:
getValidInput(selection = input("Select number 1, 2, 3. 0 exits program."))
in __name__ == "__main__":
main()
My question/issue is that while the sys.exit works to terminate the execution, I have a feeling it's not supposed to be what I'm using. I need to be able to terminate the program after user inputs "0" using a while loop. Within main(), I tried adding a false conditional to the function
call within main():
askAgain = True
while askAgain == True:
getValidInput(selection = input("Select number 1, 2, 3. 0 exits program."))
if getValidInput(selection = input("Select number 1,2, 3. 0 exits program")) == "0"
askAgain == False
and I tried adding the while loop conditional within getValidInput(), instead of main():
askAgain = True
while askAgain == True:
if selection == "1":
askAgain == True
return print("message_1")
if selection == "0"
askAgain == False
return print("goodbye")
What am I doing wrong here? I know I'm not using the loop conditional correctly, but I've tried it several different ways. The sys.exit() is my backup. The user should be able to enter inputs until 0 is entered and that should be controlled from within main(). How can I use values inputted in getValidInput to change the value of my while loop conditional in main()?
If the program is required to run infinitely until the user inputs 0, your idea to use a boolean variable was already in a right path. However, you can utilize the getValidInput() function to return/assign whether the program should stop or continue running.
Assigning the variable selection in the function call inside the main() function is not needed.
One more tip is, you should be more careful on the brackets.
import sys
def getValidInput(selection):
if selection == "1":
print("message_1")
elif selection == "2":
print("message_2")
elif selection == "3":
print("message_3")
elif selection == "0":
print("goodbye")
else:
print("That is not a valid option.")
# Use this if-else block to determine whether your function should continue running or stop
if selection == '0':
return False
else:
return True
def main():
askAgain = True
while askAgain == True:
askAgain = getValidInput(input("Select number 1, 2, 3. 0 exits program."))
if __name__ == "__main__":
main()
You don't need to have the while loop in your helper function. Your helper function is supposed to do one thing, which is just to check the answer and do something.
What you can do is instead of system.exit, each condition return a bool value and pass it to askAgain.
askAgain = getValidateInput()
Finally a small thing, to follow PEP8 rule, you should use snake case: so asg_again, get_validate_input instead.

How to use a variable across multiple functions [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 months ago.
I am trying to use two variables (i, and q) across three functions. I want to test whether i and q are valid after each input . If they are then they will be added to list and the while loop continues. If they are not valid Then the function will stop and all input will be taken and presented. I have tried to make both i and q global variables but it does not seem to work as it is saying that "i" is not defined. How do I check the i and q variables in separate functions?
Any help would be really appreciated as I am only new and thought this should work.
I didn't know what to add so I have put down the three functions in full below:
Updated:
def add_item():
code_inputed = []
quan_inputed = []
VC()
VQ()
vc_result = VC(I)
vq_result = VQ(q)
while True:
if i != "END":
if vc_result == True and vq_result == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif vc_result == True and vq_result == False:
print("Invalid Quanity")
break
elif vc_result == False and vq_result == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
return code_inputed,quan_inputed
def VC():
i = input("enter code: ")
minimum = 0
maxiumum = 39
if i == "END":
return False
elif int(i) > minimum and int(i) <= maximum:
True
else:
False
def VQ():
q = input("enter quantity: ")
minimum = 0
maxiumum = 49
if int(q) > minimum and int(q):
True
else:
False
Thank you for any help
Please read this W3Schools - Python global variables for a better understanding of how global variables work.
I think the problem with your code is, you should initialize your variables i and q first, before the add_item() function, and then get them from the global scope using the global keyword in the add_item function too.
i = 0
def add_item():
global i
Plus, you want to recheck your add_item() conditions,
while True:
i = input("enter code: ")
return i
if i != "END":
q = input("enter quantity: ")
return q # your code stops at this return
VC()
VQ()
if VC == True and VQ == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif VC == True and VQ == False:
print("Invalid Quanity")
break
elif VC == False and VQ == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
P.S. you actually don't have to use global variables in this context, you can just pass the values as functions arguments.
Looks like you need some help here. First of all the global keyword is for functions where you are setting the global variable. Also, forget about globals. Pass i and q to the functions directly. Then set those calls equal to variables and check those variables.
vc_result = VC(i)
vq_result = VQ(q)
if vc_result == True and vq_result == True:
...
Plus, return immediately exits the function so no processing will continue. Those should be removed. I recommend reviewing tutorials on python functions to fill in your knowledge.

Why Can't I break out of the loop?

Python beginner here. Sorry if it's a basic python concept
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
Although the input is 'y' the loop doesn't stop.
You need to write global over, so function run() will change global variable
over = False
def run():
global over
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
You shouldn't be using a global variable here. Return a boolean, and call run as the condition of the loop. (At this point, you may want to reconsider the name run as well.)
def run():
user_input = input("Over? (y/n)")
return user_input == 'y'
while run():
...
You are setting the local variable over inside the function run(), but you aren't passing it out to the scope from which it was called. Instead return the value to the calling scope like this:
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
else:
over = False
return over
while not over:
over = run()

'elif' not working inside 'while' loop [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I am trying to create a program; however, even when 'y' or 'yes' is entered, the code still goes to the 'n'/'no' loop. Any suggestions?
no = input("How many messages?")
intNo = int(no)
msgno = input("2 different msgs? [y/n]:")
message = input("Message:")
message2 = input("Message 2:")
run = True
pyautogui.click(x=980, y=805, button='left')
while run == True:
if msgno.lower() == "n" or "no":
pyautogui.typewrite(message, interval=0.00001)
pyautogui.press('enter')
intNo = intNo - 1
if intNo <= 0:
run = False
elif msgno.lower() == "y" or "yes":
no = no / 2
pyautogui.typewrite(message, interval=0.00001)
pyautogui.press('enter')
pyautogui.typewrite(message2, interval=0.00001)
pyautogui.press('enter')
intNo = intNo - 1
if intNo <= 0:
run = False
You have to add two conditional statements to each If statement. Like this: if msgo.lower() == 'yes' or msgo.lower() == 'y' If you have just a variable that exists or a value, it will default to True, so where "no" was defaulted to True and went into the code-block.

Extreme newbie - Python code skipping to the end (syntax issue?) [duplicate]

This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
When I run the following code, it skips to the end and simply prints "Thanks for playing!"
I'm sure it's something super obvious that I've missed, any ideas? I am using Python 2.7.6.
Thanks.
import random
def roll (sides = 6):
numberRolled = random.randint(1,sides)
return numberRolled
def main():
sides = 6
rolling = True
while rolling:
roll_again = raw_input("Press Enter to roll, or Q to quit.")
if roll_again.lower() != "q":
numberRolled = roll(sides)
print ("You rolled a " + numberRolled)
else:
rolling = False
print ("Thanks for playing!")
Python in itself has no concept of a main method. When it reads your code, it imports random, defines a method named roll, defines another method named main, then prints "Thanks for playing". It does nothing else, unless you tell it to
If you want to call main(), you'll need to do this yourself. Traditionally (to work with other code that might want to import yours as a module), it would look like this:
import random
def roll():
...
def main():
...
if __name__ == '__main__':
main()
print("Thanks for playing")
That will check if the module name is __main__ (which is true for the main script) and call your main method
You need to add if __name__ == '__main__:', and call main() from there:
import random
def roll (sides = 6):
numberRolled = random.randint(1,sides)
return numberRolled
def main():
sides = 6
rolling = True
while rolling:
roll_again = raw_input("Press Enter to roll, or Q to quit.")
if roll_again.lower() != "q":
numberRolled = roll(sides)
print ("You rolled a " + numberRolled)
else:
rolling = False
if __name__ == '__main__':
main()
print ("Thanks for playing!")
For details as to why and how it works, please see:
- what-does-if-name-main-do
- tutorial name == main
- python documentation
You need to run main
if __name__ == "__main__":
main()

Categories

Resources