Saltar a contenido

02 - First Real Program

What this session is

About 45 minutes. You'll learn three things: variables (storing data), types (kinds of data), and the f-strings Python uses for building text with values in it. By the end you'll have written a program that uses all three.

Why variables exist

Programs do things with data. To do things with data, you have to store it somewhere named, so you can refer to it later.

That's all a "variable" is: a name attached to a piece of data.

A small program with variables

Create a new file called greet.py. Type this in:

name = "Alice"
age = 30
print(name, "is", age, "years old")

Run it:

python greet.py

You should see:

Alice is 30 years old

What's new here

Two lines you haven't seen before:

name = "Alice"
age = 30

Let's unpack name = "Alice":

  • name is the name of a new variable.
  • = is the assignment operator. Read it as "is set to."
  • "Alice" is the value we're putting into it. The double quotes mean it's text (a "string").

So name = "Alice" reads as: "set name to the text Alice."

age = 30 does the same with a number. No quotes around 30 - numbers don't take quotes.

The last line:

print(name, "is", age, "years old")

print can take multiple things separated by commas, and it prints them with spaces in between. We give it four things - the value of name, the text "is", the value of age, and the text "years old". Out comes one line with all four glued together by spaces.

Types: what kind of thing is this?

Every value in Python has a type. The type tells Python what kind of thing it is and what you can do with it.

You'll meet many types over time. The first four you need to know:

Type What it holds Example values
int whole numbers (positive, negative, or zero) 0, 42, -7, 1000
float numbers with a decimal point 3.14, -0.5, 0.0
str text in quotes "hello", '', "a long sentence"
bool one of two values True, False (note capital T/F)

Notice you didn't have to tell Python the type. Python figured it out from the value. This is called dynamic typing - types are tracked at runtime, not declared in source.

In the REPL you can ask:

>>> type("hello")
<class 'str'>
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type(True)
<class 'bool'>

What you can do with numbers

The usual arithmetic works:

x = 10
y = 3
print(x + y)   # 13
print(x - y)   # 7
print(x * y)   # 30
print(x / y)   # 3.3333... - true division (returns float)
print(x // y)  # 3        - integer division (drops remainder)
print(x % y)   # 1        - modulo (remainder)
print(x ** y)  # 1000     - exponentiation (10 to the 3rd)

That # 13 part is a comment - anything after # on a line is ignored by Python. Comments are how you leave notes for yourself in the code.

Two things to notice:

  • Python has two division operators. / always returns a float (decimal); // does integer division (drops remainder). 10 / 3 is 3.333...; 10 // 3 is 3. Many other languages only have one division operator and it surprises beginners; Python's choice is friendlier.
  • ** is exponentiation. x ** 2 is x squared.

What you can do with strings

You can stick two strings together with +:

greeting = "hello"
name = "world"
message = greeting + ", " + name
print(message)   # hello, world

The technical word for "stick two strings together" is concatenate.

You can repeat a string with *:

print("ha" * 3)   # hahaha

You cannot mix freely:

n = 5
print("items: " + n)   # ERROR

The error: TypeError: can only concatenate str (not "int") to str. The fix: convert the number to a string first. Two ways.

Way one - str():

print("items: " + str(n))   # items: 5

Way two - f-strings (the modern, preferred way):

print(f"items: {n}")        # items: 5

An f-string (formatted string literal) starts with f before the opening quote. Inside the string, anything in { } is treated as Python code - its value gets inserted. You'll use f-strings constantly.

name = "Alice"
age = 30
print(f"{name} is {age} years old")
# Alice is 30 years old

You can put expressions in the braces, not just variable names:

print(f"next year, {name} will be {age + 1}")

And you can format numbers:

pi = 3.14159
print(f"pi is approximately {pi:.2f}")   # pi is approximately 3.14

The :.2f after the variable means "format as a float with 2 decimal places." There are many such format codes; you don't need to memorize them - look them up when you need them.

What you can do with booleans

A bool is just True or False (note the capitals - Python is picky). You'll use them in decisions (next page). For now:

is_ready = True
has_permission = False
print(is_ready, has_permission)   # True False

Exercise

In a new file called me.py:

Write a program that:

  1. Has a variable for your name (a string).
  2. Has a variable for your favorite number (an int).
  3. Has a variable for whether it's morning right now (a bool).
  4. Prints a line like: "Hi, I'm Victor, my favorite number is 7, and yes (True) it's morning."

Try it two ways: - First with multiple arguments to print (print("Hi, I'm", name, ...)). - Then with an f-string: print(f"Hi, I'm {name}, ...").

Don't skip this. The act of typing is the learning.

What you might wonder

"What's the difference between single and double quotes?" None. 'hello' and "hello" are identical. Pick one and be consistent; switch when you need the other quote inside ("don't" is easier than 'don\'t').

"Why does 10 / 3 return a float?" Python's designers picked the friendlier default: math behaves like math. If you want integer division, use //. Some other languages (Go, C) make / integer-only and surprise beginners by losing decimals; Python doesn't.

"What happens if I never use a variable I declared?" Python doesn't complain. (Go does.) This is a small downside - you can have typo bugs (naem instead of name) that don't surface until you actually use the typo'd variable. Tools called "linters" (page 11) catch this for you.

"Can a variable hold different types over time?" Yes - Python is dynamically typed. You can do x = 5 then later x = "hello" and Python doesn't mind. This is flexibility; it's also a source of bugs. The discipline is: pick a type per variable and stick with it. (We'll meet type hints in page 04 - Python's optional way to declare what type a variable holds.)

Done

You can now: - Make variables and give them values. - Tell apart the four basic types: int, float, str, bool. - Do arithmetic, including Python's two division operators. - Stick strings together with + and repeat with *. - Build a string with f-strings and {expression} placeholders.

Next page: making your program decide and repeat.

Next: Decisions and loops →

Comments