1

I have a simple script called cel2fer to convert Celsius to Fahrenheit . It looks like this:

Celsius = int(raw_input("Enter a temperature in Celsius: "))
Fahrenheit = 9.0/5.0 * Celsius + 32
print Fahrenheit

To run you type cel2fer <ENTER> in a terminal, then type a number like 10, then <ENTER>, then it outputs the answer. How can I modify this so you type cel2fer 10 <ENTER> and then outputs the answer?

Basically how can I accept something as an input that goes after the script?

clayton33
  • 4,176
  • 10
  • 45
  • 64

1 Answers1

1

You need to use sys.argv, a.k.a, the list of command line arguments.

import sys

InputValue = sys.argv[1] if len(sys.argv) > 1 else raw_input("Enter a temperature in Celsius: ")

Celsius = float(InputValue)
Fahrenheit = 9.0/5.0 * Celsius + 32
print Fahrenheit

This way, if you enter a argument through the command line, the answer will be printed without querying the user. But, if you don't do so, then the program will query the user.

You may have a reading here for more detailed information on the command line arguments.

I hope this has led a light on you!

Edit: Added support for float input values.

3442
  • 8,248
  • 2
  • 19
  • 41