10

I'm just playing with input and variables. I'm trying to run a simple function:

slope = (y2-y1)/(x2-x1)

I'd like to prompt the user to enter y2, y1, x2 and x1. What is the simplest, cleanest way to do this?

starbeamrainbowlabs
  • 5,692
  • 8
  • 42
  • 73
Zack Shapiro
  • 371
  • 4
  • 5
  • 14

4 Answers4

25

You can use the input() function to prompt the user for input, and float to convert the user input from a string to a float:

x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))

If you're using python 2, use raw_input() instead.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
carl
  • 49,756
  • 17
  • 74
  • 82
4

This is the simplest way:

 x1 = float(raw_input("Enter x1: "))

Note that the raw_input() function returns a string, which is converted to a floating point number with float(). If you type something other than a number, you will get an exception:

>>> float(raw_input())
a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for float(): a

If you're using Python 3 (it sounds like you are), use input instead of raw_input.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

If the user is entering the inputs in just one line with space as delimiting word between those inputs, you can write:

val1, val2, val3 = raw_input().split(' ')

Now, you can change it to:

val = float(val1)

The awesome trick is that in this way you don't waste your space creating a new list and storing your values in that and then fetching it.

tuomastik
  • 4,559
  • 5
  • 36
  • 48
0

You can use:

foo=input('Please enter a value:')

Where the string 'Please enter a value:' would be your message, and foo would be your variables.

joshim5
  • 2,292
  • 4
  • 28
  • 40
  • 4
    ...and if you enter `import os, sys; os.unlink(sys.argv[0])` instead of a number after the prompt, your script will delete itself (at least in Python 2.x). – Sven Marnach Jan 19 '11 at 01:46
  • My answer is in relation to Python 3. – joshim5 Jan 19 '11 at 02:07
  • And my comment incorrect anyway. I just wanted to make the point that this is inherently insecure in Python 2.x. For Python 3.x, you should convert the result to a float. (The correct version of the above would have been `__import__("os").unlink(__import__("sys").argv[0])`, since only an expression gets evaluated.) – Sven Marnach Jan 19 '11 at 02:08