When I run the below program it does input verification correctly and it performs the Collatz Sequence just fine. The issue is that it doesn't loop back to the beginning. I have tried removing the "break" in the second part, I have tried moving the second block around, and other small stuff, but I can't get it to go back to the input again to start over.
#Collatz Sequence
import sys
#main part of input and processing number
print ('Collatz Sequence, Y\'all!')
try:
while True:
print ('Please type in an integer greater than 1. Type (q) to quit.')
number = input()
if number == 'q':
print ('OK, see ya!')
sys.exit() # quit the program
if number.isdecimal() == True: #checks that input is a number
number = int(number)
break #breaks out of loop
print ('Please type in a number')
while True:
maybe = number%2
#print ('DEBUG ' + 'maybe is ' + str (maybe) + ' number is ' + str (number))
if number == 1:
print (' ')
print (' ')
print ('Final answer is 1.')
print (' ')
print ('Let\'s do it again:')
print (' ')
break
elif maybe == 0:
print (' ')
print (str(number) + ' is even.')
number = number//2
elif maybe == 1:
print (' ')
print (str(number) + ' is odd.')
number = 3 * number + 1
print ('Recalculating')
except KeyboardInterrupt:
sys.exit()
Try making your logic simpler and you will see your problem. Your current logic is:
try:
while True:
<get number>
if <want to quit>: sys.exit()
if <number is good>: break
while True:
if <done>: break
<step>
except KeyboardInterrupt:
sys.exit()
It sounds like you want something more like
try:
while True:
while True:
<get number>
if <want to quit>: sys.exit()
if <number is good>: break
while True:
if <done>: break
<step>
except KeyboardInterrupt:
sys.exit()
You are confusing the fact that you use loops to get input and calculate the path with needing to use a loop to continue that process. Functions would make this much more obvious.
Related
So I have the following code where chalnum (short for challenge number) is a randomly generated number. You have to try to get that number through a sequence of inputs (finalnum2). But for some reason, it always thinks the numbers aren't equal even when they are.
chal = input('Would you like a challenge number? (y/n) ')
if 'ye' in chal or chal == 'y':
str = 'Try to get %s \n'
chalnum = round(uniform(5, 5000))
print(str % colored(chalnum, attrs=['underline']))
else:
chalnum = 0
print('\n')
some more code where you make your number, then:
finalnum2 = round(num/ex_num2)
(chalnum, finalnum2)
if finalnum2 == chalnum:
chalcomp = (colored('Congrats! You completed the challenge!', 'green'))
for i in range(chalcomp):
print(chalcomp[i], sep='', end='', flush=True); sleep(0.14)
elif chalnum == 0:
pass
elif finalnum2 > chalnum or finalnum2 < chalnum:
chalfail = (colored('Oh no! It looks like you failed the challenge!', 'red'))
for i in range(chalfail):
print(chalfail[i], sep='', end='', flush=True); sleep(0.14)
else:
raise Exception
Please keep in mind that I am a beginner so if it's a stupid mistake please don't be harsh.
possible that they both in different types like 24!='24'
Use typecasting and convert into say
if int(finalnum2) == int(chalnum):
Comparison would go well in this case.
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)
I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')
I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).
I made a small program in Python (.py) and converted it into a Windows executable file (.exe) using Py2exe. It asks for a string and then outputs a string -- very simple! -- and works flawlessly in Python.
However, when the exe file finishes execution in the command window, the command window closes automatically before I can get a glimpse of its output (I assume it does print the output because, like I said, it works flawlessly in Python).
How can I prevent this from happening? I assume I need to change my code, but what exactly do I need to add to it?
Here is my code, in case it helps you to see it (it's a word-wrapper):
import string
def insertNewlines(text, lineLength):
if text == '':
return ''
elif len(text) <= lineLength:
return text
elif text[lineLength] == ' ':
return text[:lineLength] + '\n' + insertNewlines(text[lineLength+1:], lineLength)
elif text[lineLength-1] == ' ':
return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
else:
if string.find(text, ' ', lineLength) == -1:
return text
else:
return text[:string.find(text,' ',lineLength)+1] + '\n' + insertNewlines(text[string.find(text,' ',lineLength)+1:], lineLength)
print
if __name__ == '__main__':
text = str(raw_input("Enter text to word-wrap: "))
lineLength = int(raw_input("Enter number of characters per line: "))
print
print insertNewlines(text, lineLength)
Thank you.
The simplest way is probably to use raw_input() just before your program finishes. It will wait until you hit enter before closing.
if __name__ == '__main__':
text = str(raw_input("Enter text to word-wrap: "))
lineLength = int(raw_input("Enter number of characters per line: "))
print
print insertNewlines(text, lineLength)
raw_input()
Just put this at the end of your code:
junk = raw_input ("Hit ENTER to exit: ")
In other words, your main segment should be:
if __name__ == '__main__':
text = str(raw_input("Enter text to word-wrap: "))
lineLength = int(raw_input("Enter number of characters per line: "))
print
print insertNewlines(text, lineLength)
junk = raw_input ("Press ENTER to continue: ")
This is what I use in my scripts:
#### windows only ####
import msvcrt
def readch(echo=True):
"Get a single character on Windows."
while msvcrt.kbhit():
msvcrt.getch()
ch = msvcrt.getch()
while ch in b'\x00\xe0':
msvcrt.getch()
ch = msvcrt.getch()
if echo:
msvcrt.putch(ch)
return ch.decode()
def pause(prompt='Press any key to continue . . .'):
if prompt:
print prompt,
readch()
######################
Sometimes though, I just use the following to make the window stay open for a short time before closing.
import time
time.sleep(3)