How to point from one module to the next - python

I'm trying to make a password system for a program. I have the first half working so when I punch in the code it opens my file. After that the program asks for the password again instead of moving on to the next module which is supposed to close the file. Here's what I have
import os
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
except Exception as e:
print (str(e))
while True:
choice = int(input("Close? (y/n): "))
if (choice<='y'):
if choice =='y':
os.system('TASKKILL /F /IM C:\\restriced access')
I want it to kind of appear as an "if/then" kinda statement. For example if the password is entered correctly it opens the file `os.startfile('C:\restriced access') then points to the next module to give the option to close.

"While True" just keeps looping infinitely. As soon as you open the file it'll go back to the beginning of that loop and ask for your password again. If you want it to break from that loop if they get the password correct you need to add a "break" after your startfile line. I'm also not sure why you check their password twice. If you want it to exit the loop after attempting to open the file whether it succeeds or not, add a "finally" block after your exception handler.
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))

Your while loop is while True:. This will never exit unless you explicitly exit from it. You want to add a break in it like so:
os.startfile('C:\\restriced access')
break

Great to see you learn python.
The reason is because the while loop doesn't have a break in it.
Then again avoid opening files in a loop.
Also the nested if makes it hard to debug.
Also checkout pep8.
havent made any code changes.
import os
while True:
choice = int(input("Enter Password: "))
if (choice<1124):
continue
if choice ==1124:
try: os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
break
while True:
choice = input("Close? (y/n): ")
if (choice=='y'):
break

Related

Why does python raw_input function gives questionline twice as output?

With the help of https://stackoverflow.com/a/22391379/9088305 and APT command line interface-like yes/no input? I have been able to build a little script that wait for a while but can be interrupted by pressing enter.
import sys, select, os, time
from distutils.util import strtobool
for i in range(100):
sys.stdout.write("\r")
sys.stdout.write("Wait for {:2d} seconds. Press Enter to continue".format(i))
sys.stdout.flush()
time.sleep(1)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
check = 0
while not check:
userin = raw_input("Are you sure you want to continue? (yes/no)")
try:
bool = strtobool(userin)
if bool:
check = 1
break
else:
print("Let's continue then")
time.sleep(1)
break
except ValueError:
check = 0
print("Choose either yes or no, please")
if check == 1:
break
print "\nDone!"
However, upon execution, it will alway give the question once, with an ""Choose either yes or no, please" after that:
Are you sure you want to continue? (yes/no)Choose either yes or no, please Are you sure you want to continue? (yes/no)
I haven't been able to figure out why this is. Can someone help me out? So that I can just get "Are you sure you want to continue? (yes/no)" once and I can put in yes or no.
Thanks in advance!

Python 3.4 How do you limit user input

I have made a program which requires the user to go and come back after completing the command, I would like the user to press ENTER to then continue the programme, to do this I used a normal Input command that does not record the answer. However I would like it if the user cannot enter any text, the only thing they can do is press ENTER to proceed.
input("Please charge your device, when you are finished, press ENTER on the keyboard")
You can try to write an if loop that checks whatever the input is enter: For example:
import tty
import sys
import termios
orig_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin)
x = input("Text")
while x != chr(13): # Enter
x=sys.stdin.read(1)[0]
print("ERROR PLEASE TRY AGAIN")
x = input("Text")
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
You might like to check this answer by #Turn at the question here: https://stackoverflow.com/a/34497639/2080764

How to turn my if statement into a while or for loop?

So the program I'm trying to make is that an user can enter a path WHICH HAS TO BE CORRECT to continue. I thought that I would make a simple prompt to tell the user it is either a valid path or not.
This is my prompt code:
if Path.find("Global") == -1:
continue
else:
print "Not a valid path."
Of course I can't use continue in there but I just don't get how to make this prompt as a loop. The idea was that if the Path contains the word "Global" the program continues with another action and if it doesn't contain the word it will tell the user a message and tell the program to stop (break).
def get_path():
Path = raw_input("Please select the correct path: ")
if Path.find("Global") == -1:
# "Tell the user a message and tell the program to stop".
print('{0} is not a correct path.'.format(Path))
return
# "the program continues with another action."
print('{0} is a correct path.'.format(Path))
You can break the loop unless your input matches condition, like this:
while True:
if 'Global' in raw_input('Enter a valid path: '):
continue
else:
print 'Not a valid path.'
break
Try this:
Path = raw_input("Please enter a valid Path")
while Path.find("Global") == -1:
print "This is not a valid Path."
Path = raw_input("Please enter a valid Path")

python-help learning how to deal with errors using try-except [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am brand new to the site and python. I'm learning how to deal with errors using try-except. I'm asking for inputs to open a file and search for a line. This is the program i have now. It mostly works...
try:
file_str = input("Open what file:")
input_file = open(file_str) # potential user error
find_line_str = input("Which line (integer):")
find_line_int = int(find_line_str) # potential user error
line_count_int = 1
for line_str in input_file:
if line_count_int == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
break
line_count_int += 1
else: # get here if line sought doesn't exist
print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
except IOError:
while True:
file_str = input("That file was not found. Please try again:")
except ValueError:
find_line_str = input("Invalid line value. Please try again:")
print("End of the program")
Originally, if there was an error it would say "invalid entry, end of program" Now I am trying to make the program keep asking for inputs until the user gets it right.
With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.
How do I get it to go back and run the for loop after it receives a valid input? Ive been trying to figure this out for hours I really appreciate the help.
In a nutshell
while True:
try:
#code
break #success case
except IOError:
#error display
#no break, the loop goes on
Updated version of your own script. Added a while loop. The following script will start again from top in case of ValueError or IOError.
while True:
try:
file_str = input("Open what file:")
input_file = open(file_str) # potential user error
find_line_str = input("Which line (integer):")
find_line_int = int(find_line_str) # potential user error
line_count_int = 1
for line_str in input_file:
if line_count_int == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
break
line_count_int += 1
else: # get here if line sought doesn't exist
print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
break
except IOError:
print "That file was not found. Please try again:"
except ValueError:
print "Invalid line value. Please try again:"
print("End of the program")
With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.
Of course it would:
except IOError:
while True:
file_str = input("That file was not found. Please try again:")
Once the first IOError is occurred there is no way to break from that while loop.
As a rule of thumb, you should keep the least amount of lines in each try block. This way you will have a finer control over what line raised the exception.
In this case, you should try opening the file in a while loop, breaking if succeeding and keep looping if an exception occurred:
while True:
file_str = input("Open what file:")
try:
input_file = open(file_str) # potential user error
break
except IOError:
print('File not found. Try again')
# rest of code
Your try/except(s) should be put in a while-condition loop.
To exit the loop you can then either:
set a condition flag as True before entering the loop and as False as soon as entry is ok - you'll keep looping on any error
or put a 'break' at the end of a correct entry within a 'while True:' loop
In both case, you should accept also quitting the loop on some request from the user (something as a 'cancel' use-case).

sys.exit in python console

Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:
if name == "lin":
do stuff
elif name == "static":
do other stuff
else:
sys.exit("error in input argument name, Unknown name")
If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.
I use Python 2.7 with Spyder on MAC.
Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?
Thanks for help
Not sure this is what you should be using sys.exit for. This function basically just throws a special exception (SystemExit) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit. It displays the message and then goes back to the REPL.
Rather than using sys.exit you should do something like:
def do_something(name):
if name == "lin":
print("do stuff")
elif name == "static":
print("do other stuff")
else:
raise ValueError("Unknown name: {}".format(name))
while True:
name = raw_input("enter a name: ")
try:
do_something(name)
except ValueError as e:
print("There was a problem with your input.")
print(e)
else:
print("success")
break # exit loop
You need to import sys. The following works for me:
import sys
name="dave"
if name == "lin":
print "do stuff"
elif name == "static":
print "do other stuff"
else:
sys.exit("error in input argument name, Unknown name")

Categories

Resources