EDIT: I know there were previous similar questions. Except that it was asked by people who already know Python. I did try the duplicated answer you suggested and it is not working (nothing display in console when I ran it with command line argument). That solution seems to ignore input value via cmd line arg. I could do the job easily in other languages. But for this exercise, I need a Python script. Please help me to write a script ready for use. Sorry if this sounds like a careless request. I do know programming, the trouble here is that I don't know anything about Python.
This is to be used in a streaming exercise with the Hive language (part of Hadoop). Here is the specs:
The script take the value from the command line argument and return the result to standard output
Add thousand separator when the value is compatible with numerical value, otherwise re-output the same input value unchanged.
Example:
$ InsertThousandSeparator.py 386
386
$ InsertThousandSeparator.py 1234567
1,234,567
$ InsertThousandSeparator.py 123ABC
123ABC
$ InsertThousandSeparator.py 123ABC456
123ABC456
$ InsertThousandSeparator.py Hello
Hello
$ InsertThousandSeparator.py 12345.67
12,345.67
The last example with decimal, if it's too complicate to code, this could be skipped.
Thank you very much in advance for any help.
OK, here you are - a script for Python 2.7. But please try to ask one question at a time next time, OK?
import sys
arg = sys.argv[1] # get first command line parameter
if arg.isdigit(): # integer value
value = int(sys.argv[1])
else:
try:
value = float(sys.argv[1]) # try float conversion
except ValueError: # if that fails
value = None # mark value as unusable
if value is not None:
print "{:,}".format(value) # print with thousands separator
else: # or, if not a number
print arg # print as-is.
Related
I have a few python files that take input as two ints separated by spaces, and return an int. (My class requires this.) I'm having an issue where an extra "D" appears along with my output, after I hit Ctrl-D to end the input. It's running the programs correctly, though - the output is correct.
Here's what I'm seeing:
$ python gcd_euclid.py
144 100
4D
$ python pc_1_ucsd.py
3 4
7D
Oddly...this wasn't happening yesterday, and I'm not sure if I changed anything. Does anyone have any ideas why this is happening and how to fix it?
Edit: Here is the snippet that the course provided for reading the input. I hadn't used sys.stdin before this week.
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
(they chose to use the input keyword as a variable, not me!)
I suspect it is old keyboard echo (where did the line feed go?) Try feeding shell input using something like:
command-and-args <<!EOF
input lines
!EOF
I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
In Learn Python The Hard Way (Exercise 13) the 3rd Study Drill says to "Combine raw_input with argv to make a script that gets more input from a user."
I wrote this script below, intending to have the terminal prompt the user for answers to three questions, then it would print back phrases with those answers integrated into them. However, I get an error about not having enough values to unpack when I try to run it with the following command:
python ex13.py
I understand that I need more variables to unpack in order for the script to work, so when I type this then the script works but never outputs the variables "first", "second" or "third" (which I don't want it to anyway):
python ex13.py first second third
I know how to write a script without importing argument variables, but how else can I interpret the study drill? I know I am not understanding the prompt of the study drill correctly but I'm not sure how to write the script differently or even if I am going in the right direction.
Can anyone offer some tips or advice? You don't have to give me the answer outright (I like figuring things out) but I am at a loss for the moment.
MY SCRIPT:
from sys import argv
script, color, number, shape = argv
color = raw_input("What is your favorite color? ")
number = raw_input("What is your favorite number? ")
shape = raw_input("What is your favorite shape? ")
print """
This program is called %r and it will determine your
favorite color, number and shape.
""" % script
print "Based on your answers, your favorite color is:", color
print "Your favorite number is:", number
print "And your favorite shape is a:", shape
What exactly do you want your code to do? If you want to have
$ python ex13.py
$ What is your favorite color? <yourColor>
..........
$ Your favorite color is <yourColor>
Then you need to get rid of the part where you set all those values from argv. argv is a list of the arguments passed to python when you invoke it in the command line. The fix you have in your comments sets script = ['ex13.py'] instead of 'ex13.py' for precisely this reason, you're setting script to be a list as opposed to a string.
If you want your code to run so that you pass the script arguments when you run it, you could get rid of your sections calling for raw_input (or you could leave them in, but that would overwrite their values from what you passed in the command line) Try running the code you've posted with
$ python ex13.py <yourColor> <yourNumber> <yourShape>
It should work much more closely to what you want.
As you have already solved one problem by removing the variables before the =, now the only problem is you are getting square brackets around ex13.py.
You see you have to add another variable after script before = that is without input() and the problem is solved.
Here's my python code. Could someone show me what's wrong with it.
while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude"
if date=="March 21" | date=="September 21":
sd="0° Latitude"
if date=="December 21":
sd="23.5° South Latitude"
if sd:
print sd
And Here's what happens:
>>>
Example: March 21 | What is the date?
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Solar Declination Calculater.py", line 2, in <module>
date=input("Example: March 21 | What is the date? ")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
>>>
Use raw_input instead of input :)
If you use input, then the data you
type is is interpreted as a Python
Expression which means that you
end up with gawd knows what type of
object in your target variable, and a
heck of a wide range of exceptions
that can be generated. So you should
NOT use input unless you're putting
something in for temporary testing, to
be used only by someone who knows a
bit about Python expressions.
raw_input always returns a string
because, heck, that's what you always
type in ... but then you can easily
convert it to the specific type you
want, and catch the specific
exceptions that may occur. Hopefully
with that explanation, it's a
no-brainer to know which you should
use.
Reference
Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.
Indent it! first. That would take care of your SyntaxError.
Apart from that there are couple of other problems in your program.
Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.
You are using certain 8bit characters in your script like 0°. You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.
Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.
I also think that reading Python tutorial might helpful to you. :)
Sample Code
#-*- coding: latin1 -*-
while 1:
date=raw_input("Example: March 21 | What is the date? ")
if date.lower() == "march 21":
....
I had this error, because of a missing closing parenthesis on a line.
I started off having an issue with a line saying:
invalid syntax (<string>, line ...)?
at the end of my script.
I deleted that line, then got the EOF message.
While #simon's answer is most helpful in Python 2, raw_input is not present in Python 3. I'd suggest doing the following to make sure your code works equally well in Python 2 and Python 3:
First, pip install future:
$ pip install future
Second: import input from future.builtins
# my_file.py
from future.builtins import input
str_value = input('Type something in: ')
And for the specific example listed above:
# example.py
from future.builtins import input
my_date = input("Example: March 21 | What is the date? ")
I'm using the follow code to get Python 2 and 3 compatibility
if sys.version_info < (3, 0):
input = raw_input
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
i came across the same thing and i figured out what is the issue. When we use the method input, the response we should type should be in double quotes. Like in your line
date=input("Example: March 21 | What is the date? ")
You should type when prompted on console "12/12/2015" - note the " thing before and after. This way it will take that as a string and process it as expected. I am not sure if this is limitation of this input method - but it works this way.
Hope it helps
After the first if statement instead of typing "if" type "elif" and then it should work.
Ex.
` while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
sd="0° Latitude"
elif date=="December 21":
sd="23.5° South Latitude"
elif sd:
print sd `
What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.
Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.
Switched off for use in Python/IDLE
#input=raw_input
And of course switched on for use in terminal.
input=raw_input
I'm not sure if it will always work, but its a possible solution for simple programs or scripts.
Check the version of your Compiler.
if you are dealing with Python2 then use -
n= raw_input("Enter your Input: ")
if you are dealing with python3 use -
n= input("Enter your Input: ")
Check if all the parameters of functions are defined before they are called.
I faced this problem while practicing Kaggle.
This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:
$ echo '
> print "The Code:"
> PrintScript() # What would this function look like?
> for i in range(5):
> print i,
> print "!"
> ' | python
and get an output like this:
The Code:
print "The Code:"
PrintScript() # What would this function look like?
for i in range(5):
print i,
print "!"
0 1 2 3 4 5 !
I suspect that this probably can't be done, but given python's introspection capabilities, I was curious to know whether it extended to this level.
That's the closest I'm getting:
echo 'import __main__,inspect;print inspect.getsource(__main__)' | python
which fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.
Update:
The dis module is supposed to give you a disassembly of all functions in a module, but even that one isn't seeing any code:
$ echo -e 'import __main__,dis;print dis.dis(__main__)' | python
None
And even when I throw in a function:
$ echo -e "import __main__,dis;print dis.dis(__main__)\ndef x():\n pass" | python
None
Yes, it is indeed possible to write a program which outputs it's own source. You don't need even introspection for this tasks, you just need to be able to print computed strings (works with every language).
The technique is called Quine and here is a rather short example in Python:
quine = 'quine = %r\r\nprint quine %% quine'
print quine % quine
But quines aren't limited to such simple programs. They can do much more, for example printing their own source backwards and so on... :)
print open(__file__).read(),
This will work on UNIX systems I think, but I'm not sure about Windows. The trailing comma makes sure that the source code is printed exactly, without an extra trailing newline.
Just realized (based on the comments below) that this does not work if your source code comes from sys.stdin, which is exactly what you were asking for. In that case, you might take advantage of some of the ideas outlined on this page about quines (programs printing their own source codes) in Python, but none of the solutions would be a single function that just works. A language-independent discussion is here.
So, in short, no, I don't think this is possible with a single function if your source code comes from the standard input. There might be a possibility to access the interpreted form of your program as a Python code object and translate that back into source form, but the translated form will almost surely not match the original file contents exactly. (For instance, the comments and the shebang line would definitely be stripped away).
closest you can get is using readline to interrogate the command history if available from what i can see e.g. but i suspect this may not contain stuff piped into the session and would only work for interactive sessions anyway