Why Can't I break out of the loop? - python

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

Related

Using Python for default parameters

I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()

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.

Changing variable dynamically via user input in python

I want to produce an endless loop that would to different things depending on some user input.
When the .py is executed the loop starts and does some 'main' programm and the input window opens for the user. When typing 'alt1' the loop jumps in to the function 'main_alt1' and so on.
user_input = 'main'
user_input = input()
while True:
if user_input == 'main'
main()
elif user_input == 'alt1'
main_alt1()
elif user_input == 'exit'
exit()
The problem here is that the input is either given once before the loop (like in the example) or it stops the loop when the input is inside the loop until the input is given.
Does anyone has a smart way to do something like that. It doesn't need to be with input().
I think it's better to use a class to process the user input:
(I updated the code with the process method)
from multiprocessing import Process
from time import sleep
class InvalidAction(Exception):
pass
class Cmd:
def __init__(self):
self._active_thread = None
def _action_hi(self):
while True:
print('Hi!')
sleep(1)
def _action_ping(self):
while True:
print('Pong!')
sleep(1)
#staticmethod
def _get_method_name(action):
return f'_action_{action}'
def process(self, action: str):
method_name = self._get_method_name(action)
if not hasattr(self, method_name):
raise InvalidAction
if self._active_thread is not None:
self._active_thread.terminate()
self._active_thread = Process(target = getattr(self, method_name, None))
self._active_thread.start()
def main():
cmd = Cmd()
while True:
try:
user_input = input('Action: ')
cmd.process(user_input)
except InvalidAction as e:
print(f'Invalid Action!')
except KeyboardInterrupt:
print('Exiting the loop.')
break
except Exception as e:
print(f'Something went wrong - {e}')
if __name__ == '__main__':
main()
user_input = 'main'
user_input = input()
while True:
if user_input == 'main'
main()
elif user_input == 'alt1'
main_alt1()
elif user_input == 'exit'
exit()
user_input = input()
Taking the the input again at the end of loop works. Since it is while True it runs infinitely till user enters exit
after calling every function you can again take update from user to change variable
import keyboard
while True:
if keyboard.read_key() == 'a':
main_alt1()
elif keyboard.read_key() == 'b':
main_alt2()
elif keyboard.read_key() == 'e':
exit()
else:
main()

Global variables in multiples functions in Python

i will try to explain my situation with examples:
Im using global to declare a variable but this work only in a function, when i try to another sub function doesnt work.
register.py
def main():
alprint = input("Enter something: ")
if alprint == "a":
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alCheck()
alTest()
main()
and content.py
from register import CheckTest
if CheckTest == "ad":
print("You are welcome!")
When i declare this variable checkTest in a sub function(function, alTest()) of main, using global and importing to another file, it doesnt work, i tried a lot of things, but nothing.
It would work, except that if the user enters something other than a for the first input, CheckTest is not defined, so it gives an ImportError. You might want to try something like this instead:
def main():
global CheckTest, CheckDot
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alprint = input("Enter something: ")
if alprint == "a":
alCheck()
alTest()
else:
CheckTest = None
CheckDot = None
main()
This way, CheckTest, and CheckDot are always defined.

Categories

Resources