How do I exit out of an entire program through a function? - python

I'm a noob to python and I wanted to make a "digital signboard". I only have "A" and "B" right now.
I don't know how to exit out of the program completely using sys.exit(). I guess it only exits out of the function and then continues on to the next line of code to ask for the next letter. I want it to exit the program entirely once "end" is inputted but still have the letters displayed before it exits.
import time, sys
def getLetter(letter):
while True:
if letter =='A'or letter=='a':
print('<A>')
return
break
elif letter =='B'or letter=='b':
print('<B>')
return
break
elif letter == 'space':
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
print('')
time.sleep(0.1)
elif letter == 'end':
sys.exit('Signboard Terminated')
#instructions
print('Welcome to virtual signboard\n')
time.sleep(0.5)
print('Instructions:')
time.sleep(0.5)
print('Enter each character individually (max: 10 characters).')
time.sleep(0.5)
print('To enter a space, type "space"')
time.sleep(0.5)
print('To finish, type "end"')
print('Enter first character:')
firstLetter=input()
time.sleep(0.2)
print('\nEnter second character:')
secondLetter=input()
time.sleep(0.2)
print('\nEnter third character:')
thirdLetter=input()
time.sleep(0.2)
#getting output
output=getLetter(firstLetter)
output=getLetter(secondLetter)
output=getLetter(thirdLetter)
So ideally this would happen:
Enter first character:
A
Enter second character:
end
and the whole program would stop there without asking for the second and third character but display A only

The sys.exit indeed is used to terminate the entire program. In your case the flow of the program is probably invalid. Please, compare to the code below and decide which workflow should your application apply to.
import sys
def getLetter(letter):
if letter =='A'or letter=='a':
print('<A>')
elif letter =='B'or letter=='b':
print('<B>')
elif letter == 'space':
print('<space>')
elif letter == 'end':
sys.exit('Signboard Terminated')
else:
print("<Other number>")
#instructions
print('Welcome to virtual signboard\n')
print('Instructions:')
print('Enter each character individually (max: 10 characters).')
print('To enter a space, type "space"')
print('To finish, type "end"')
while True:
print('Enter character:')
character = input()
#getting output
getLetter(character)

First of all, there is no need to import sys just for exitting the program. use exit('Signboard Terminated') to terminate with the message Signboard Terminated. If i'm correct the code seems fine, because you are taking character inputs first, and then passing it into the function to print the signboard. If you need to end the program when the user types end you will have to check each user inputs, that if he typed the word end before calling the getLetter() function.
i.e.
def exitFun(letter):
if letter.lower() == "end":
exit('terminated')
print('Enter first character:')
firstLetter=input()
exitFun(firstLetter)
time.sleep(0.2)
print('\nEnter second character:')
secondLetter=input()
exitFun(secondLetter)
time.sleep(0.2)

Related

How do I exit() the python script within terminal when I press the 'Escape' key?

The objective here is to exit the script once the escape key is pressed, without having to make a guess for a letter first. I think is problem is that the input() isn't detecting 'esc' as a keypress. So at the moment I have to guess a letter, press 'enter', then press the 'esc' kay to exit the script.
def main():
import random
import keyboard
import sys
# Main program code....
# Keep asking the player until all letters are guessed
while display != wordChosen:
guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))[0]
guess = guess.lower()
#Add the players guess to the list of used letters
used.extend(guess)
print ("Attempts: ")
print (attempts)
while True:
if keyboard.read_key() == 'esc':
print("Exiting...")
sys.exit(0) # this exits your program with exit code 0
# Search through the letters in answer
for i in range(len(wordChosen)):
if wordChosen[i] == guess:
display = display[0:i] + guess + display[i+1:]
print("Used letters: ")
print(used)
# Search through the letters in answer
for i in range(len(wordChosen)):
if wordChosen[i] == guess:
display = display[0:i] + guess + display[i+1:]
print("Used letters: ")
print(used)
# Print the string with guessed letters (with spaces in between))
print(" ".join(display))
# more code....
This is the terminal output below, I believe the issue is getting the input() for '.guess' to acknowledge the keyboard press of 'esc', but I'm not sure how to do this? As you can see the '^[' is picked up but doesn't instantly exit the script unless I press 'enter'. Apologies, wasn't sure how to properly paste in text from terminal.
Please enter a guess for the 5 letter word: ^[
Attempts:
0
Exiting...
^[%
Do you have try this kind of example in documentation:
keyboard.add_hotkey('esc', lambda: exit(0))

Input doesn't match pass code when they are the same

I just started python last week and made this code project to test my learning. This code is supposed to display a Zombie Apocalypse and the user arrives at the military base. While proving that they are human, the code generates a random 5 number pass code to make the game unique every time. The user has to type to code in, kind of like a CAPTCHA. But when I run the code, after the user types the pass code and presses enter, the pass code entering part of the code starts to repeat. I think this may be because of the while loop if the user gets the pass code wrong. I don't have much experience to see the problem. I tried rewriting the whole thing, it didn't even try to work because of so many syntax error messages. If you can please help me it would be appreciated.
I also am working on it on replit, so you can check the code there:
https://replit.com/#PratikKharel/Something2?v=1
import time
import sys
import random
def typing(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.07)
def fasttyping(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.02)
def fastertyping(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.005)
passcode = "".join(str(random.randint(1, 9)) for _ in range(5))
typing("Hello fellow surviver.")
time.sleep(0.8)
print("")
typing("Welcome to the Zombie Military Base: ")
time.sleep(0.8)
print("")
typing("Lambda 17 ")
time.sleep(1)
print("")
typing("This is where you will begin your survival story. ")
print("")
time.sleep(1)
passwordright = False
typing(f"Type [{passcode}] to verify as a Human")
time.sleep(0.5)
typing(".")
time.sleep(0.3)
typing(".")
time.sleep(0.3)
typing(".")
time.sleep(0.3)
def start():
print("")
typing(">>> ")
o = (int(input("")))
if o != passcode:
typing("Please try again.")
print("")
start()
elif o == passcode:
passwordright = True
fasttyping("##$____!#%$!#___WE_ARE_COMING_FOR_YOU__#$##$___##$")
time.sleep(0.2)
sys.stdout.flush()
time.sleep(1)
fastertyping(
'\r____________________________________________________________')
time.sleep(0.5)
print("")
typing("Since you are here, you will need a nickname.")
print("")
fasttyping("What will !##$%^&#")
time.sleep(0.2)
sys.stdout.flush()
time.sleep(1)
fastertyping('\rWhat will your name be?')
while passwordright == False:
start()
start()
That's because you are trying to compare between different data types at:
if o != passcode:
o is of type int, while passcode is a string.
Just delete the int casting in o = (int(input(""))) to:
o = (input())

while loop, asking user if he wants to repeat the program problem

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.

Loop Input until Parameter is met or User Input

I want my program to either wait 10 seconds before moving on, or break the loop by user input
try:
while True:
afkseconds = 0
time.sleep(1)
afkseconds +=1
if afkseconds == 10:
Timer()
except KeyboardInterrupt:
pass
newTaskIO = input('Y/N: ')
newTaskIO = newTaskIO.lower()
if newTaskIO == 'y':
taskName = input('Enter the name of the task: ')
taskDescription = input('Enter a brief description, or press enter to continue: ')
The program enters the while Loop, adding a second to the "afksecond" variable. The idea is once the afksecond variable = 10, the loop breaks and performs the specified function.
Either that or the user enters "y" or "n" to break the loop and continue with the next phase of the program. I cannot figure out the logic to get this to work. Please advicse

How do I run one def function inside of a different def function in python?

I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
Here is my code:
import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed")
timer = True
attempt = input("The timer has started!\nType here: ")
while timer == True:
time.sleep(1)
timec = timec +1
if attempt == "abcdefghijklmnopqrstuvwxyz":
timer = False
print("you completed the alphabet correctly in", timec,"seconds!")
else:
print("There was a mistake! \nTry again: ")
The issue is that it will not let me enter the alphabet. In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work. Any help is appreciated
import time
start = time.time()
attempt = input("Start typing now: ")
finish = time.time()
if attempt == "abcdefghijklmnopqrstuvwxyz":
print "Well done, that took you %s seconds.", round(finish-start, 4)
else:
print "Sorry, there where errors."
Think carefuly about that you are dong
You ask for a user-entered string
While timer equals True, you sleep for one second and increase the count. In this loop, you do not change the timer.
Obviously, once user stopped entering the alphabet and pressed enter, you start an infinite loop. Thus, nothing seems to happen.
As other answers suggested, the best solution would be to save the time right before prompting user to enter the alphabet and compare it to the time after he finished.
you could do something like:
import datetime
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"')
init_time = datetime.datetime.now()
success_time = None
while True:
user_input = input('The timer has started!\nType here: ')
if user_input == alphabet:
success_time = datetime.datetime.now() - init_time
break
else:
continue
print('you did it in %s' % success_time)

Categories

Resources