Lesson 1
What is programming?
Programming means we compute. To compute means to calculate.
Computing always has three parts:
- Input
- Calculation
- Output
Your first program
print outputs whatever you give it. Here the input is the text "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:
The simple way to print the same sentence many times:
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:
Numbers come in two kinds:
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:
Try removing the int() calls and entering 2 and 2. You'll get 22 — string gluing, not addition. Same +, different types, different behavior.