Python variables
I am trying to create a basic program that will generate a number based on variables entered by the user. Formula
a = b / (c * d)
This is the formula for finding the heat capacity, while b=energy
, c=mass
and d= change in temperature
.
So my problem is that I am not making this program for myself, otherwise I could simply assign each variable a numeric:
b= 1200
c= 13
d= 2
And then do it a = a = b / (c * d)
.
My goal is to create a program for others who don't know the formula yet, so they can just enter the numbers themselves. Example. I want to b = X
. X
is the number entered by the user of the program. However, I must first define X
as a variable - I want it to be unknown, or based on what the person is entering. I do not want to b
, c
or d
have assigned values. This is a very simple scripting process that I know but I'm new to Python.
I think you want something like this:
b = float(raw_input("Energy? "))
c = float(raw_input("Mass? "))
d = float(raw_input("Change in temperature? "))
print "Specific heat: %f" % (b / (c * d))
- raw_input () prompts the user and returns the entered value
- float () converts the value to float (if possible, if not, this will throw an exception and exit the program)
- The "% f" on the last line formats the argument as a floating point value, where "argument" is the value of the expression following the off-line% (ie "(b / (c * d)))
source to share
The simplest approach is to precede the formula with a snippet
b = input("Enter b:")
c = input("Enter c:")
d = input("Enter d:")
A few notes:
- this will require an I / O console, so your best bet is to run the script from the console
- input () calls the entered string eval () 'ed, which means it treats processes as if it were a Python expression. This is useful for numbers, but can have confusing side effects; use
raw_input()
insteadfloat()
.
source to share
b = float(raw_input("Please enter a value: "))
a = b / (c*d)
print a
raw_input()
prompts the user for input if you use it in the console
float()
tries to convert a parameter (in this case user input) to a float. the rest should be pretty straightforward.
Try it. Welcome to Python :)
source to share