simple python script not working properly

Discussion in 'Programmer's Corner' started by donut, Jun 12, 2012.

  1. donut

    Thread Starter Member

    May 23, 2012
    51
    0
    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?
     
  2. Markd77

    Senior Member

    Sep 7, 2009
    2,803
    594
    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>
     
    donut likes this.
  3. donut

    Thread Starter Member

    May 23, 2012
    51
    0
    that did the trick. just curious how/why did you consider using str(distance/rate)

    and why didnt the training source I'm using

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

    know that the script wasnt going to work without str(distance/rate)?
     
  4. Markd77

    Senior Member

    Sep 7, 2009
    2,803
    594
    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>
     
Loading...