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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With