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()
Related
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.
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()
So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.
i am building scientific calculator. After performing the operation it ask do u want to go back in main menu or Exit
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
continue
else:
break
when user press y it go back to main menu otherwise exit
You can`t use break and continue in function, read tutorial
instead, you can use check in your main loop, and your function must return True or False
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
return True
else:
return False
while True: # your main loop
# some other code
# check on exit
if Again():
continue
else:
break
This can work!
class Cal:
def main_menu(self):
print ("I am in main menu")
def again(self):
x = raw_input("Go back to main menu(Y/N)")
if x == 'y':
self.main_menu()
if __name__ == '__main__':
c = Cal()
c.again()
When you will enter y it will go to the main menu.
Also, continue and break will not work here as they both are applied in loops.
You can use raw_input instead of input as input does not accept string values.
I'm quite new to Python and I am trying to make a little adventure game, just to develop my skills. So, for my game, I want there to be a few options, and the player will pick one and it will return a different result. However, the options will not always be the same, so I decided to make a function, so the options and results could differ. Here is the code for my function:
def action(act1, act2, act3, act4):
loop = True
while loop:
print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
act1
return
elif player_action == '2':
act2
return
elif player_action == '3':
act3
return
elif player_action == '4':
act4
return
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
The parameters are functions for what I want to print out.
My problem is, when I call this function and run the code, Python executes each function in every if and elif statement. For example, when I call this:
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action(home_act1(), home_act2(), home_act3(), home_act4())
I run the program and it does this:
Welcome to the wilderness!
Welcome to the town!
Welcome to the store!
You left the adventure.
Process finished with exit code 0
It seems to just be running all four of my parameters, it worked before I made it a function but something isn't working right.
Thanks to any help!
In this line:
action(home_act1(), home_act2(), home_act3(), home_act4())
you are actually calling each function and passing the result (None in each case, since that is the default.
Try passing just the functions (home_act instead of home_act()), then in the loop body actually call act().
The reason you have all 4 outputs and then the code exiting is because you call all four home_act functions immediately by doing action(home_act1(), home_act2(), home_act3(), home_act4()), which executes one after another and exits the program due to the exit() in home_act4().
Another thing that is problematic is that you return after each action within the while-loop, which means the code would have stopped once the user has done one single action.
Fixing these problems results in the following code:
def action():
loop = True
while loop:
#print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
home_act1() # call the respective action function here
elif player_action == '2':
home_act2()
elif player_action == '3':
home_act3()
elif player_action == '4':
home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action()
Good luck with further coding :)
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
def action():
loop = True
while loop:
# print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
return home_act1() #or you can remove the return and carry on in the function
elif player_action == '2':
return home_act2()
elif player_action == '3':
return home_act3()
elif player_action == '4':
return home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
action()
You can return a function call:
def functionToCall():
print('Ok function called')
def function():
return functionToCall()
function()