How to handle no input using input() function in Python? - python

I tried to write a program which requests user to choose an option, however, Python always show an error message if user choose nothing and only input ENTER. Here is an example
tmp=input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
print tmp, type(tmp) #test input
if len(str(tmp)) == 0:
tmp=0
if tmp == 1:
print "User choose to create a C++ program.\n"
DFT_TYPE=".cpp"
elif tmp ==2:
print "User choose to create a Python program.\n"
DFT_TYPE=".py"
elif tmp ==3:
print "User choose to create a PERL scripts.\n"
DFT_TYPE=".pl"
else:
print "User choose incorrectly. Default Python program would be created.\n"
DFT_TYPE=".py"
if I input ENTER only, I got error message like below
Traceback (most recent call last): File "./wcpp.py", line 17, in <module>
tmp=input() File "<string>", line 0
^ SyntaxError: unexpected EOF while parsing
How to handle such case if user input nothing? Any further suggestion would be appreciated.

Since you are using python 2, use raw_input() instead of input().
tmp=raw_input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
...
...
if tmp!='':
tmp = int(tmp)
pass #do your stuff here
else:
pass #no user input, user pressed enter without any input.
The reason you are getting error is because in python2 input() tries to run the input statement as a Python expression.
So, when user gives no input, it fails.

you can use raw_input with a default value
x = raw_input() or 'default_value'

Related

CS50 taqueria task - input of eof halts program

I am trying to solve the taqueria task for the Harvard CS50 python course. It generally works, but check50 spits out the following:
:( input of EOF halts program
Cause
expected exit code 0, not 1
This is my code:
menu = {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00
}
def main():
item = get_dish("Item: ")
total = 0
try:
while True:
try:
total += menu[item.title()]
print("$" + str(round(total, 3)))
item = get_dish("Item: ")
except KeyError:
item = get_dish("Item: ")
pass
except EOFError:
pass
def get_dish(prompt):
dish = input(prompt)
while dish.lower() in menu == False:
dish = input(prompt)
else:
return dish
main()
I cannot end input to induce an EOFError in VS Code on GitHub myself by pressing ctrl + z or ctrl + d. Therefore, I cannot handle it myself in the try... except block. It might be a problem with the VS Code itself. Maybe there are other ways to end input, induce an EORError and handle it in the code.
Method 1: provide an empty input file
You can reproduce an EOFError in your code by giving it an empty input file.
In the VSCode terminal using bash, or at a bash prompt:
$ python script_name.py < /dev/null
Item: Traceback (most recent call last):
File "C:\Users\me\sandboxes\scratch\script_name.py", line 35, in <module>
main()
File "C:\Users\me\sandboxes\scratch\script_name.py", line 14, in main
item = get_dish("Item: ")
File "C:\Users\me\sandboxes\scratch\script_name.py", line 29, in get_dish
dish = input(prompt)
EOFError: EOF when reading a line
Or if you're using the Windows cmd prompt, in a VSCode terminal or otherwise:
> python script_name.py < NUL
Item: Traceback (most recent call last):
File "C:\Users\me\sandboxes\scratch\script_name.py", line 35, in <module>
main()
File "C:\Users\me\sandboxes\scratch\script_name.py", line 14, in main
item = get_dish("Item: ")
File "C:\Users\me\sandboxes\scratch\script_name.py", line 29, in get_dish
dish = input(prompt)
EOFError
In both cases above, you could also create a file to use as input, and have it empty when that's what you want to test, but /dev/null / NUL is the bash/cmd name for the special system empty file you can always use instead of creating one.
And as you see in these traces, the problem is that your first call to get_dish() is not in a try/except block.
Method 2: interactively end the input stream
In cmd, just type ^Z+Enter and that'll trigger the EOF and reproduce the same error.
To my surprise, in bash the equivalent ^D doesn't automatically do the same thing. I expected it would, as is typical, but instead when you type ^D+Enter you get "\x04" as the string returned by input(). So I guess if your program wants to accept ^D+Enter to mean end of file, it would have to explicitly do so with a piece of logic like if dish == "\x04": raise EOFError in get_dish(), but I understand you're just trying to debug your code and reproduce the error check50 gives you, so this is not too helpful.
So... if you're working in a bash terminal, use method 1 above.
When you've got things working, you'll probably want to add something to get_dish() for the user to signify they're done, like accepting q to mean done, because as it is, your user won't be able to exit the program cleanly, at least not from a bash terminal.

What could be my invalid syntax error in my code?

I am having problems with a simple program I wrote but do not know where the problem is, and it is giving me a Syntax error.
This is my code:
username = {}
temp = True
while temp:
name = input("Please input your username: ")
response = input("What is the place you want to visit? ")
username[name] = response
end = input("Do you want to end the program? Yes/No ")
if end == 'Yes':
temp = False
print("These are the results of the poll: ")
for names, responses in username.items():
print(names + " wants to go to " + responses)
This is my error:
File "<stdin>", line 1
/usr/local/bin/python3 "/Users/eric/Python Notes/Notes.py"
^
SyntaxError: invalid syntax
Check out the accepted answer here:
syntax error when using command line in python
Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.
There are also some VSCode-specific tips here:
Invalid Syntax error when running python from inside Visual Studio Code

How can I make my python script wait until I tell it it to continue in the terminal?

I'm trying to make the the second print statement wait until I press enter in the command line but I keep getting an unexpected EOF error.
print "hi"
continu = input("Press Enter to continue!")
print "hi"
Here is my traceback
Traceback (most recent call last):
File "save_cookies.py", line 2, in <module>
continu = input("Press Enter to continue!")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
It looks like your are mixing python2 and python3 statements.
For python2 you need to use raw_input (PEP 3111):
print "hi"
raw_input("Press Enter to continue!")
print "hi"
For python3 instead, you need to adjust the syntax on the print (PEP 3105):
print("hi")
input("Press Enter to continue!")
print("hi")
Try using raw_input() instead of input().

How to use sys.argv in python to check length of arguments so it can run as script?

Ok so here is part of my code (I have imported sys)
if __name__ == '__main__':
MyCaesarCipher = CaesarCipher() #MyCaesarCipher IS a CaesarCipher()
if len(sys.argv) >1:
#what will it check?
Done = False
while not Done:
print('C Clear All')
print('L Load Encrypted File')
print('R Read Decrypted File')
print('S Store Encrypted File')
print('W Write Decrypted File')
print('O Output Encrypted Text')
print('P Print Decrypted Text')
print('E Encrypt Decrypted Text')
print('D Decrypted Encrypted Text')
print('Q Quit')
print('----------------')
print('Enter Choice>')
So the thing is I want to do is if the command line length is more than 1, the program runs as a script.
This is the instruction:
If no command line arguments are input, then the script enters menu
mode. If more than 1 command line argument (anything other than script
name) is provided during the run of the script it enters single run
mode.
I do not know what this means, though.
What is sys.arvg:
The list of command line arguments passed to a Python script. argv[0] is the script name.
Demo:
File Name: 1.py
import sys
if __name__=="__main__":
print "command arguments:", sys.argv
Output:
$ python 1.py arg1 arg2
command arguments: ['1.py', 'arg1', 'arg2']
$ python 1.py
command arguments: ['1.py']
Your problem is, we have to run code by Command Line Argument and by Menu also.
When User provided the Enter Choice from the command line then use provided value to next process.
If User not provided the Enter Choice from the command line then ask User to Enter Choice from the Menu.
Demo:
File Name: 1.py
import sys
if __name__ == '__main__':
try:
arg_command = sys.argv[1]
except IndexError:
arg_command = ""
Done = False
while not Done:
if arg_command=="":
print('\nMenu')
print('C Clear All')
print('L Load Encrypted File')
print('Q Quit')
print('----------------')
print('Enter Choice>')
command = raw_input('Enter Selection> ').strip()[0].upper()
else:
command = arg_command
#- set arg value to empty to run Menu option again.
arg_command = ""
if command == 'C':
print "In Clear All event."
elif command == 'L':
print "In Clear All event."
elif command == "Q":
break
else:
print "Wrong Selection."
Output:
Enter Choice given from the Command Line:
$ python 1.py C
In Clear All event.
Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$
No Command Line argument.
$ python 1.py
Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> l
In Clear All event.
Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$
Here's the thing, when you're learning a language like this, you can often get by pretty well with just printing out things you don't really understand.
Try this:
Step 1) Make a program that looks like this:
import sys
if __name__ == '__main__':
for idx, arg in enumerate(sys.argv):
print("arg #{} is {}".format(idx, arg))
print len(sys.argv)
After that, run your program from the command line like this:
$ python3 test_script.py
Then, run it like this:
$ python3 test_script.py somearg someother andanother etc "23908452359"
What you discover may be useful to perform this task you are looking to resolve.
Lastly, "menu mode" sounds like the script is going to take input from the user. Thus, you'll need to use input() to do that. It also sounds like you need to come to some decision about when to use menu mode or not, which you've already started to do with your if-test above.
Experiment a bit, though, and you'll figure it out.
The instructions want the script to use the command line arguments to execute the script.
python script.py [arg1] [arg2] [arg3] ....
The args are accessible through sys.argv.
sys.argv = ['script.py', '[arg1]', '[arg2]', '[arg3]']
You will need to use a command line interface instead of the menu interface when args are present.
Since you seem to be pretty new to python here's a simple example using your code. You'll have to complete the menu and the actual code for the menu options but it does use sys.argv
import sys
def menu():
Done = False
while not Done:
print('C Clear All')
print('L Load Encrypted File')
print('R Read Decrypted File')
print('S Store Encrypted File')
print('W Write Decrypted File')
print('O Output Encrypted Text')
print('P Print Decrypted Text')
print('E Encrypt Decrypted Text')
print('D Decrypted Encrypted Text')
print('Q Quit')
print('----------------')
print('Enter Choice>') #should get user input here
Done = True
if __name__=="__main__" :
if len(sys.argv) > 1 :
#Here if an argument is present run it or load the menu
print "run whatever option was entered on the commandline"
else:
menu()
First of all you have to understand what argv is, try creating this script, and call it learning_argv.py
import sys
print(sys.argv)
now try running the script like this:
$ python3 learning_argv.py
$ python3 learning_argv.py a
$ python3 learning_argv.py a b c
$ python3 learning_argv.py AWESOME TEXT
See what argv is?
What you're doing when you test if the length of argv is bigger than one, is basically testing if you're receiving anything beyond the script name.
In the future, you could create a similar structure you created for your menu, to treat arguments sent directly from the command line.
take a look at this quick tutorial in order to better understand argv.

How does a user input a filename?

I've written code for an assembler, but I am still new to python.
In my code I have the user input a file that will be converted into an assembly language. I think I've almost got it working, but I can't figure out where the user enters the file name.
I'm in (what I think is) IDLE, and then when I hit F5 it runs in the shell. I'm getting an error, but I'm pretty sure it's because no file name has been entered.
Where is the user supposed to input these kinds of things? Is this done from the python shell, or from the command line, do I need to turn it into an executable?
Can someone help clarify where the user is inputting all this information?
I'll put in a segment of code, although I don't think it's necessary to answer my questions, but maybe it'll give you a better idea of my issue.
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
print 'need filename'
sys.exit(-1)
table = SymbolTable()
parser = Parser(sys.argv[1])
parser.advance()
line = 0
while parser.hasMoreCommands():
if parser.commandType() == 'L_COMMAND':
table.addEntry(parser.symbol(), line)
else:
line += 1
parser.advance()
code = Code()
parser = Parser(sys.argv[1])
parser.advance()
var_stack = 16
while parser.hasMoreCommands():
cmd_type = parser.commandType()
if cmd_type == 'A_COMMAND':
number = 32768
try:
addr = int(parser.symbol())
except:
if table.contains(parser.symbol()):
addr = table.getAddress(parser.symbol())
else:
table.addEntry(parser.symbol(), var_stack)
addr = var_stack
var_stack += 1
bin_number = bin(number | addr)[3:]
assembly = '0' + bin_number
print assembly
elif cmd_type == 'C_COMMAND':
assembly = '111'
assembly += code.comp(parser.comp())
assembly += code.dest(parser.dest())
assembly += code.jump(parser.jump())
print assembly
parser.advance()
The part to note is at the beginning lines 4-6 where it's checking the file name. So once I run my program I get 'need filename' printed to the screen and an error message that looks like this:
Traceback (most recent call last):
File "C:\Python27\Assembler.py", line 98, in <module>
sys.exit(-1)
SystemExit: -1
So where can I input the filename to avoid this error?
The way you have it, Python expects the filename as an argument:
python file.py your_file.asm
If you want to prompt for a filename, use raw_input() (or input() for Python 3):
filename = raw_input('Enter a filename: ') or 'default_file.asm'
sys.argv contains command line arguments.
So, this script has to be run through command-line, for getting input, as said by blender, use raw_input (or input) for getting input from the user, if there are not enough command-line arguments.
Something like this:
if len(sys.argv) == 1:
print "You can also give filename as a command line argument"
filename = raw_input("Enter Filename: ")
else:
filename = sys.argv[1]
And change the line
parser = Parser(sys.argv[1])
To
parser = Parser(filename)

Categories

Resources