variables, assignment, types, input/output

Try the Jupyter notebook version.

motivation

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: $18000
Approximate monthly take-home-pay = $ 1050.0
(assuming tax of 30.0 percent.

Here's one way to write the above program:

In [2]:
salary_s = input("Yearly Salary: $")
salary = float(salary_s)
tax_rate = 0.30
tax = salary * tax_rate
net = salary - tax
monthly_pay = net/12.0
print("Approximate monthly take-home-pay = $", monthly_pay)
print("(assuming tax of", (tax_rate * 100), "percent.")
Yearly Salary: $18000
Approximate monthly take-home-pay = $ 1050.0
(assuming tax of 30.0 percent.

Note the use of variables, and the descriptive variable names, like salary, tax_rate, and monthly_pay.

Also note the use of type conversions, like float(salary_s). Remember, the input() function always returns a string, no matter what the user types. So the variable salary_s is assigned the value "20000" (a string). We use the suffix _s to remind us that it is a string. When we convert it to a float on the next line, we simply remove the _s so we know that it's now a numerical values that we might expect someone's salary to be.

more examples

We can output multiple items on the same line by separating each item using a comma or by joining multiple strings together using string concatenation. The following program just gets a name from the user and then says "Hello" to the user using both of these methods:

In [4]:
name = input("What is your name? ")
print("Hello", name)
print("Hello " + name)
What is your name? Jeff
Hello Jeff
Hello Jeff

The two print() lines display the same thing (e.g., "Hello Jeff"). The first one uses a comma to separate the string "Hello" and the variable name. The second one uses string concatenation to add the string "Hello" to the string stored in name. Note that string concatenation only works if both arguments are of type str.

Here's a another example:

In [7]:
name = input("Dog's name: ")
age  = input(" Dog's age: ")
years = float(age) * 7
print("In dog years,", name, "is", age, "but in human years that's", years, "years.")
Dog's name: Rex
 Dog's age: 4
In dog years, Rex is 4 but in human years that's 28.0 years.

challenge

Write a 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.

Here is a sample output where the user entered "orange", "purple", and "smart":

    color: orange
    color: purple
adjective: smart

Roses are orange
Violets are purple
Sugar is smart
and so are you!!
In [ ]: