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

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

Related

A timer for the rocket lift off

i would like to have a countdown for my rocket to life off but i just cant make it decrease the number it only stays the same can someone help me?
print("program is writen by someone")
name = input("program is runned by")
print(name,",if you are a pilot of the project please type pilot for the next question. If you are other please type your reason/role for u being here")
x = input("what is your reason for u being here")
if x == 'pilot':
print (name,"ok wlecome to the crew")
h = input ("is the hatch closed? please answer closed or no")
if h == 'closed':
import time as t
second = int(input ("very good please enter the needed for the countdown"))
for i in range(second):
print (str(second - 1)+ "second remaining \n")
t.sleep(1)
print ("time is up")
else:
print ("please check if the hatch is close")
else:
y = input("are you 600meters away from the spacecraft?")
if y == 'yes':
print ("have a nice time watching the show")
else:
print("please stand back untill u are 600 meter away from the aircraft")
You're not using the loop variable and printing the same second-1 value every time. You can use a decreasing range, e.g.:
for i in range(second, 0, -1):
print(f'{i} seconds remaining')
time.sleep(1)
or simply a while-loop:
while second:
print(f'{second} seconds remaining')
second -= 1
time.sleep(1)
(Notice that time.sleep() is called inside the loop body)

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

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)

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)

python -- Crash when trying to deal with unexpected input

So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)

Interrupting a timer

I'm creating part of a program right now for a personal project and I need some help on one aspect of it.
Here is how the program works:
User enters the amount of time to run
User enters the text - Files are modified
Timer is started
optional User can enter "password" to interrupt the timer
Actions are reversed
I have all of the steps coded except the Timer because I'm trying to figure out the best way to do this. Ideally, I'd like the timer to be displaying a countdown, and if the user enters a certain "password" the timer is interrupted and it skips to step number 5.
Would the best way to do this be with a thread? I haven't worked much with threads in the past. I just need someway for the timer to be displayed while also giving control back to the user in case they want to enter that password.
Thanks for any help you provide.
Here's the code:
import time
import urllib
import sys
def restore():
backup = open(r'...backupfile.txt','r')
text = open(r'...file.txt', 'w+')
text.seek(0)
for line in backup:
text.write(line)
backup.close()
text.close()
text = open(r'...file.txt', 'a+')
backup = open(r'...backupfile.txt','w+')
text.seek(0)
for line in text:
backup.write(line)
backup.close()
while True:
url = raw_input('Please enter a URL: ')
try:
if url[:7] != 'http://':
urllib.urlopen('http://' + url)
else:
urllib.urlopen(url)
except IOError:
print "Not a real URL"
continue
text.write(url)
while True:
choice = raw_input('Would you like to enter another url? (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.seek(2)
continue
elif choice == 'n':
while True:
choice = raw_input('Would you to restore your file to the original backup (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.close()
restore()
sys.exit('Your file has been restored')
else:
text.close()
sys.exit('Your file has been modified')
As you can see, I haven't added the timing part yet. It's pretty straight forward, just adding urls to a text file and then closing them. If the user wants the original file, reverse() is called.
Under Windows you can use msvcrt to ask for a key. Asking for a password is actually more complex, because you have to track several keys. This program stops with F1.
import time
import msvcrt
from threading import Thread
import threading
class worker(Thread):
def __init__(self,maxsec):
self._maxsec = maxsec
Thread.__init__(self)
self._stop = threading.Event()
def run(self):
i = 1
start = time.time()
while not self.stopped():
t = time.time()
dif = t-start
time.sleep(1) # you want to take this out later (implement progressbar)
# print something once in a while
if i%2==0: print '.',
#check key pressed
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 59:
self.stop()
#do stuff
# timeout
if dif > self._maxsec:
break
i+=1
def stop(self):
print 'thread stopped'
self._stop.set()
def stopped(self):
return self._stop.isSet()
print 'number of seconds to run '
timeToRun = raw_input()
#input files
#not implemented
#run
w = worker(timeToRun)
w.run()
#reverse actions

Categories

Resources