Question

I am working on a Farenheiht-Celsius converter in Python 3. I have some example code given to me that doesn't work, but I don't know why. Here is my code:

#!home/andres/Documents/Executables
import sys
f = int(sys.argv[1])
print (f, "degrees farenheit is equal to", )
print (5.0/9*(f - 32), "degrees Celsius.")

Of course, I obtain a syntax error as follows:

Traceback (most recent call last):
  File "/home/andres/Documents/Executables/f2c.py", line 3, in <module>
    f = int(sys.argv[1])
IndexError: list index out of range
>>> 

Some stuff to note:

  1. I have a (sketchy) understanding of the sys.argv command, which is used in conjunction with command line arguments.

  2. My teacher intends for me to tun this code as such.

    $ ./f2c.py 212
    212.0 degrees farehheit is equal to 100.0 degrees celsius.

(Yes, I know the above section is not showing up as code, but I am not sure how to fix it.) 3. I am running Ubuntu, but am still getting used to it. Pardon my ignorance.

Think that's about it. Thanks!

EDIT: Here is my shell session, which may help:

andres@Beta:~/Documents/Executables$ ./f2c.py
bash: ./f2c.py: /bin/env: bad interpreter: No such file or directory
andres@Beta:~/Documents/Executables$ chmod +x f2c.py
andres@Beta:~/Documents/Executables$ ./f2c.py 12
bash: ./f2c.py: /bin/env: bad interpreter: No such file or directory
andres@Beta:~/Documents/Executables$
Was it helpful?

Solution

I believe you are running your code within the interpreter, either using an IDE or the python prompt. This will not work as sys.argv relies on calling the program from the terminal command line. When I do so your code works correctly,

[myself@localhost ~]$ python f2c.py 12
12 degrees farenheit is equal to -11.1111111111 degrees Celsius.

To run it as ./f2c.py you need to do two things,

edit your code to resemble the following

#!/usr/bin/env python

import sys
f = int(sys.argv[1])
print (f, "degrees farenheit is equal to", )
print (5.0/9*(f - 32), "degrees Celsius.")

This is a command for linux shells such as bash to call the 'env' program and tell it that we need to use python to run it

Secondly, we need to make the file executable, this is done as

chmod +x f2c.py

Now you can call as follows

[myself@localhost ~]$ ./f2c.py 12
12 degrees farenheit is equal to -11.1111111111 degrees Celsius.

BTW, the correct spelling is Fahrenheit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top