Programming Fundamentals

Variables and Data Types

↩ Back
01

What a Variable Is

Definition
Assignment

An assignment computes whatever sits on the right of the equals sign, then binds the name on the left to the result. It is an instruction, not a statement of equality.

Defining traits
Right firstPython finishes the expression on the right before the name exists.
One valueA name stands for one value at a time. Assigning again replaces what was there.
No type declaredYou never announce a type. The value brings its own.
# the right side is computed, then stored tickets = 3 price = 12.5 total = tickets * price print(total) # 37.5
Rules
Naming a Variable

A name is built from letters, digits and underscores, and it cannot start with a digit. Case matters, so total and Total are two separate names.

Accepted and rejected
NameStatusWhy
total_price✓ acceptedWords joined by underscores, the usual style in Python.
n2✓ acceptedDigits are fine anywhere except in first position.
2nd_try✕ rejectedA name cannot open with a digit.
total price✕ rejectedA space splits it into two names, and neither one parses.
class✕ rejectedReserved by the language for its own syntax.
a good name says what the value means, not what type it has
Interactive
Follow the Values

Press Step to run one line at a time. The table holds every name Python knows at that moment, together with the type of the value behind it. Watch line 4 reuse price on both sides: the old value is read, and the new one takes its place.

price = 40discount = 0.25saving = price * discountprice = price - savinglabel = "Final price: "print(label + str(price))
line 1 of 6
Memory
NameValueType
no names yet
Output
nothing printed yet
02

The Four Basic Types

Reference
int, float, str, bool
TypeHoldsWritten asWatch for
int Integer numbers, positive or negative, with no limit on size. 42 0 -7 Division with / never gives back an int.
float Numbers with a decimal part. 3.14 2.0 -0.5 Tiny rounding error is normal: 0.1 + 0.2 shows as 0.30000000000000004.
str Text of any length, including the empty text. "hello" 'a' "" "42" is text. It cannot be added to a number.
bool Logical value, either true or false. True False Capital letter required, and in arithmetic they count as 1 and 0.
Concept
The Value Carries the Type

The name has no type of its own. It points at whichever value was assigned last, so type(x) can answer differently on two lines of the same program.

x = 5 print(type(x)) # <class 'int'> x = "five" print(type(x)) # <class 'str'>

Python calls this dynamic typing. It saves you from writing the type on every line, and it moves the responsibility onto you: nothing warns you when a name that held a number now holds text, until an operation fails.

Interactive
Type Inspector

Pick an expression. Python evaluates it, and only then does the result have a type.

Value? type()?

Pick one to see what comes back.

03

Type Conversion

Definition
Conversion Functions

The functions int(), float(), str() and bool() build a new value of the type you ask for. The value they read stays as it was, so the result has to be stored or used right away.

n = "7" m = int(n) print(n, type(n)) # 7 <class 'str'> print(m, type(m)) # 7 <class 'int'> print(m + 1) # 8

Both lines print the same character on screen. Only the second value can take part in arithmetic, which is why print is a poor way to check a type and type() is a reliable one.

Rules
What Works and What Fails
ExpressionStatusWhat comes back
int("42")✓ worksGives 42. Text made only of digits converts cleanly.
int(3.9)✓ worksGives 3. The decimal part is cut off, never rounded. Use round() for that.
str(3.5)✓ worksGives "3.5". Any value at all can become text.
int("3.5")✕ failsValueError. int() reads integer numbers only, so go through int(float("3.5")).
int("hello")✕ failsValueError. There is no number to read.
"5" + 3✕ failsTypeError. Convert one of the two sides before the operation.

Falsy values

bool() is the one conversion that never fails. It returns False for 0, 0.0 and "", and True for everything else, including the text "0".

Interactive
Conversion Playground

Choose a value and a function, then run the pair. Errors are shown as Python reports them, since reading the error name is half of fixing it.

Python console
nothing run yet
04

Reading Input

Definition
input()

Calling input() pauses the program, waits for a line typed by the user, and returns that line as a str. The optional argument is printed first, as a prompt.

Always textTyping 30 gives back the two characters "30", never the number.
One lineReading ends when the user presses Enter.
Prompt optionalinput() with no argument waits without printing anything.
name = input("Your name: ") print("Hello,", name)
Pattern
Convert Where You Read

Wrapping the call keeps the rest of the program working with real numbers, so no later line has to remember that the value arrived as text.

1
Read the typed line with input().
2
Convert it to the type the program needs.
3
Store the converted value under a clear name.
4
Use that name in the arithmetic.
age = int(input("Age: ")) next_year = age + 1 print("Next year you turn", next_year)
Interactive
Run It and Answer

The program stops on the input() line and waits for you to type into the console, the way a terminal does. Answer once with a number, then run it again and answer with letters, and compare what each version does with the same reply.

age = input("Age: ")print(age + 1)
Python console
press Run to start the program

Press Run, and the program will stop and wait for your answer.

05

Working with Strings

Definition
Indexing

Each character sits at a numbered position. Counting runs from 0 at the left, and from -1 at the right, so the last character is reachable without knowing the length.

s = "PYTHON" print(s[0]) # P print(s[3]) # H print(s[-1]) # N print(len(s)) # 6
ExpressionStatusWhat comes back
s[0]✓ worksGives 'P'. The first character, always.
s[-1]✓ worksGives 'N'. The last one, whatever the length.
s[len(s)]✕ failsIndexError. Positions run to len(s) - 1, so the last one here is s[5].
Definition
Slicing

A slice returns a new string built from the characters between two positions, and every part of s[start:stop:step] can be left out.

s = "PYTHON" print(s[1:4]) # YTH print(s[:3]) # PYT print(s[3:]) # HON print(s[::2]) # PTO print(s[::-1]) # NOHTYP
start left outBegins at the first character.
stop left outRuns to the end of the string.
stepHow far to jump. A negative step walks backwards.
⚠️ Be careful

s[0:3] takes the characters at positions 0, 1 and 2, and stops just before position 3.

Interactive
Slice Explorer

Move the three controls and watch which characters survive. The row above each character shows the position counted from the left, the row below shows the same position counted from the right.

start0
stop6
step1
Expressionword[0:6] Result'PROGRA' Length6

Negative values are allowed on the sliders, and they count from the right.

Concept
Strings Never Change

A string cannot be edited in place. Every operation that looks like editing builds a new string and leaves the old one alone.

s = "python" s[0] = "P" # TypeError s.upper() # builds "PYTHON", changes nothing s = s.upper() # now s holds the new string

The second call is discarded because no name catches it. Storing the result, either back under the same name or under a new one, is what makes the change stick.


f-strings
name = "Ada" score = 9.5 print("Hi " + name + ", " + str(score)) print(f"Hi {name}, {score}")

An f before the quotes lets you drop names straight into the text, with the conversion handled for you.

Toolkit
Building Text
Operators
+Joins two strings. Both sides have to be strings.
"Bar" + "celona" gives 'Barcelona'
*Repeats a string an integer number of times.
"ab" * 3 gives 'ababab'
Common methods, press one for an example
Examplepress one Result?

Each one builds a new value and leaves the original string as it was.

06

Check Yourself

Question
Which Slice Comes Out?
The code
s = "Barcelona" print(s[2:5])
Pick one.
Challenge
Write an ID Card Program

Five lines of work, using everything on this page. The first line is written for you.

1
Ask for a name and keep it in a variable.
2
Ask for a birth year and convert the answer with int().
3
Print a greeting with the name in capitals.
4
Print the age reached in 2026.
5
Print the initial: the first character of the name, with a dot after it.
Editable program
Python console
press Run to start your program

Press Run. When the console asks something, type your answer into it and press Enter.

07

Summary

Recap
What You Can Do Now
1
Read an assignment as an instruction: compute the right side, attach the name, replace whatever the name held before.
2
Name values in a way Python accepts and a reader understands.
3
Tell int, float, str and bool apart, and check any value with type().
4
Convert between types on purpose, and predict which conversions raise ValueError.
5
Read a typed line with input() and convert it before doing arithmetic.
6
Reach any character with an index, cut any piece with a slice, and build new text with +, methods and f-strings.