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.

+2


source to share


4 answers


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)))
+6


source


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()

    instead float()

    .
+4


source


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 :)

0


source


this is a really simple way to do it and easy to understand

b= float(raw_input("Enter the energy"))
c= float(raw_input("Enter the mass"))
d= float(raw_input("Enter change in temperature"))

a = b / (c * d)
print a

      

0


source







All Articles