simple python script not working properly

Thread Starter

donut

Joined May 23, 2012
51
Using a online source to get a quick review of python from beginners perspective.

http://oopweb.com/Python/Documents/easytut/VolumeFrames.html

just trying to run the following script:

#This programs calculates rate and distance problems

print "Input a rate and a distance"

rate = input("Rate:")

distance = input("Distance:")

print "Time:"

distance/rate

I expect this to happen:

Input a rate and a distance

Rate:5

Distance:10

Time: 2

Instead I get this

Input a rate and a distance

Rate:5

Distance:10

Time:


Why am I not getting a value for time when i run the script?
 

Markd77

Joined Sep 7, 2009
2,806
Try this:
print "Time:" + str(distance/rate)

With the code as it is the result will be rounded to the nearest integer.
<ed>Actually it depends on what you type at the input:
Rate 12 and distance 1000 gives a different result to rate 12.00 and distance 1000.00</ed>
 

Markd77

Joined Sep 7, 2009
2,806
I tried distance/rate and that gave an error, and I had a vague recollection that using str was the way to fix it.
Have a look here:
http://www.tutorialspoint.com/python/python_variable_types.htm

Here is how to make it always display the result with fraction:
print "Time:" + str(float(distance)/float(rate))
There are probably other ways.

<ed> It will probably cause an error if text is entered, so it's usually worth checking input to make sure it's compatible. </ed>
 
Top