We need variables to hold data, either from the user or some other source. When writing programs, we certainly don't want to hard code all data. Input and output are how we get interesting data into and out of our programs.
As an example, here's a program that gets data from the user (yearly salary = 20000), does a calculation with the data, and then displays the results:
Yearly Salary: $20000
Approx monthly take-home-pay = $1166.67
(assuming tax of 30%)
Here's one way to write the above program:
usersalary = raw_input("Yearly Salary: $")
gross = float(usersalary)
taxrate = 0.30
tax = gross*taxrate
net = gross - tax
monthlypay = net/12.0
print("Approx monthly take-home-pay = $%.2f" % (monthlypay))
print("(assuming tax of %.0f%%)" % (taxrate * 100))
Note the use of variables, and the descriptive variable names, like usersalary
,
taxrate
, and monthlypay
.
Also note the use of type conversions, like float(usersalary)
. Remember, the
raw_input()
function always returns a string, no matter what the user types.
So the variable usersalary
is assigned the value "20000"
(a string).
Output is much easier if we use string formatting. The following program just gets a name from the user and then says "Hello":
name = raw_input("What is your name? ")
print("Hello, " + name + "!")
print("Hello, %s!" % (name))
The two print()
lines display the same thing (e.g., "Hello, Jeff!").
The second one uses a string placeholder (%s
), instead of concatenating
strings together using the +
operator.
Here's a better example of using string formatting:
name = raw_input("Dog's name: ")
age = raw_input(" Dog's age: ")
years = float(age) * 7
print("%s's age in human years: %d" % (name,years))
Instead of converting everything to strings and concatenating, we
use the %s
placeholder for the name
variable, and the %d
('d' for
decimal integer) for the years
variable.
Write a poem.py
program that asks the user for two colors and
an adjective, and then outputs the "roses are red" poem using the
data from the user.
In the example below, the user enters "orange", "purple", and "smart":
$ python poem.py
color: orange
color: purple
adjective: smart
Roses are orange
Violets are purple
Sugar is smart
and so are you!!