Programed interactivity

You don't need to store all values in the program. A program can learn by interacting with the user and asking him what it needs to give him a result.

The raw_input() function is what is needed to make a program ask for a text value:

name = raw_input("Type your name: ")

print "Hello", name

When run this program will output whatever you type:

[cpn@dkt my_programs]$ python input.py
Type your name: cpn
Hello cpn

The mileage calculus can be made generic to be used for any car. Just make the program ask the right questions:

gallon_price = 2.41

print
print "This program calculates a car mileage"
print

# A line starting with a # is a comment
# Use it to comment important parts of your code

#
# The raw_input() function asks the user for a text
# As a text can't be multiplied or divided the
# float() function tranforms the text into a decimal number
#
distance = float(raw_input("How many miles were measured ? "))
print
consumed = float(raw_input("How many gallons of gas were consumed ? "))

mpg = distance / consumed
cost = gallon_price / mpg

print
print "mileage is", mpg, "miles per gallon"
print
print "cost is US$", cost, "per mile"
print

Save it as mileage_interactive.py and run. Note that if you're using Windows just type mileage_interactive.py at the command prompt and if using Linux type python mileage_interactive.py

[cpn@dkt my_programs]$ python mileage_interactive.py

This program calculates a car mileage

How many miles were measured ? 221.27

How many gallons of gas were consumed ? 10.87

mileage is 20.356025759 miles per gallon

cost is US$ 0.118392461698 per mile

[cpn@dkt my_programs]$
0 Komentar untuk "Programed interactivity"

Back To Top