Skip to content

Lesson 1

What is programming?

Programming means we compute. To compute means to calculate.

Computing always has three parts:

  1. Input
  2. Calculation
  3. Output
1 + 1 = 2

Your first program

print outputs whatever you give it. Here the input is the text "hello world":

print("hello world")

Variables

A variable is memory in the computer. The = sign assigns a value to a variable. Here "I will not talk in class" is the value:

phrase = "I will not talk in class"

The simple way to print the same sentence many times:

print("I will not talk in class")

The smart way — store it once, use it many times:

print(phrase)
print(phrase)
print(phrase)
print(phrase)
print(phrase)
print(phrase)
print(phrase)
print(phrase)

Data types

In the human world we have text and numbers. Computers have their own names for them:

Human Computer data type
text string
number integer, float
true/false boolean

Watch what + does with different types:

print(1 + 1)               # prints 2
print("hello" + " world")  # prints hello world
print("2" + "2")           # prints 22

Numbers come in two kinds:

age = 13       # whole number   =>  integer
height = 1.75  # decimal number =>  float

Getting input

input always gives you a string, even when the user types a number. We have to convert the string to an integer before we can do math:

first_number = input("first number?")
second_number = input("second number?")

# we have to convert string to integer
print(int(first_number) + int(second_number))

Type conversion

To the computer, "2" and 2 are different things: "2" is a string (text that happens to look like a number), while 2 is an integer it can do math with. int() converts a string into a real integer — this is called type conversion (or casting). Since input() always returns a string, we convert before adding:

print(2 + 2)      # integers => math      => 4
print("2" + "2")  # strings  => glue them => 22

Try removing the int() calls and entering 2 and 2. You'll get 22 — string gluing, not addition. Same +, different types, different behavior.