Szkoła Podstawowa nr 1 w Jarosławiu

Programming in Python (variables • conditions • loops • functions • lists)🇵🇱

1. What source code is and how to run a program

Tip: If you run a file by double‑clicking and the window closes too quickly, you can add this at the end of the program:
input("\nTo finish, press Enter")
This will keep the window open until you press Enter.

2. Variables – storing data in memory

A variable is a named part of memory (a memory cell) where the computer stores a value. A variable has a name and a current value.

Step 1: Assign a value to a variable

number = 23

Step 2: Change (overwrite) the value

number = number + 1
print(number)
Important: The statement number = number + 1 is not a mathematical equation. It is an instruction: “take the current value of the variable, add 1, and store the result back in the same variable”.

Data types (Python recognizes them automatically)

TypeWhat it storesExample
intintegersyear = 2021
floatreal numbers (with a dot)height = 159.5
strtext (a string)surname = "Kowalski"
Note on writing numbers: in Python we use a dot for the decimal part, e.g. 34.5, not 34,5.

3. Displaying information – print()

The print() function displays text and calculation results in the console.

total = 10 + 5
print("The total is:", total)

New line character \n

4. Arithmetic operators

OperatorOperationExampleWhat you get
+addition23 + 5679
-subtraction987 - 233754
*multiplication432 * 62592
//integer division (cuts off the fractional part)55 // 318
/division “with a fraction”55 / 318.3333...
%remainder (modulo)37 % 41

Note: plus with text

If variables are strings (str), then + means concatenation (joining strings):

print("car" + "pet")   # result: carpet

5. Entering data from the keyboard – input()

input() displays a prompt and waits until the user types something. It always returns text (type str).

Step 1: Read text

city = input("Enter the name of a city: ")
print(city)

Step 2: Read an integer

number = int(input("Enter a number: "))

Step 3: Read a real number

average = float(input("Enter your grade average: "))
Why do you sometimes get different results?
If you do number = input(...), then number is a string. In that case number + number means concatenation (e.g. "34" + "34" → "3434").
If you do number = int(input(...)), then number + number means addition (34 + 34 → 68).

6. Conditional statement – if / else

A conditional statement lets the program make a decision based on a condition (true/false).

Full form (with else)

if condition:
    list_of_instructions1
else:
    list_of_instructions2
next_instruction

Simplified form (without else)

if condition:
    list_of_instructions1
next_instruction
Indentation: The block after if (and after else) must be indented. Most commonly we use 4 spaces. No indentation = syntax error.

Comparison and logical operators

GroupOperatorMeaningExample
Comparisons==equala == b
!=not equala != b
<less thana < b
>greater thana > b
>=greater than or equala >= b
<=less than or equala <= b
Logicalorora < -5 or a > 5
andanda > 0 and a < 10
notnegation (NOT)not a == 5

Example 1: the larger of two numbers (an exercise with a condition)

a = int(input("Enter the first number: "))
b = int(input("Enter a second number different from the first: "))

if a > b:
    print("The first number is larger", a)
else:
    print("The second number is larger", b)

input("\n\nTo finish, press Enter")

Example 2: positive or non‑positive number

x = int(input("Enter an integer: "))

if x > 0:
    print("Positive number")
else:
    print("Non‑positive number")

7. Iterations – the for loop (repeating actions)

An iteration is repeating the same operation. In Python, we most often use the for loop for this.

General form

for variable in list_of_values:
    list_of_instructions

list_of_values can be a real list (e.g. [0,1,2,3,4]) or a sequence generated by range().

for over a “real” list

for i in [0, 1, 2, 3, 4]:
    print(i)

range() – the most common number generator

for i in range(5):
    print(i)          # 0 1 2 3 4

for i in range(15, 55):
    print(i)          # 15 ... 54

for i in range(1, 20, 2):
    print(i)          # 1 3 5 ... 19
Note about the end of range(): the number end is not included in the sequence (we always end at end-1).

Example: five rectangles (repeated area calculation)

for i in range(5):
    x = int(input("Enter the length of the first side: "))
    y = int(input("Enter the length of the second side: "))
    area = x * y
    print("The area of a plot with side", x, "and side", y, "is:", area)

input("\n\nTo finish, press Enter")

8. Functions – organizing your program

A function (a subprogram) is a separated piece of code with a clear name. Thanks to functions, it is easier to keep order and reuse the same solution many times.

Function definition

def function_name(parameter_list):
    list_of_instructions
    return value

A function that returns a value (with return) – example: the volume of a cube

def cube(a):
    return a * a * a

side = int(input("Enter the cube side length: "))
print("The volume of a cube with side length", side, "is:", cube(side))
input("\n\nPress Enter to finish")

A function that does not return a value (without return) – example: “drawing” characters

def show_characters(chars):
    for i in range(1, 11):
        print(chars * i)

emoji = input("Enter the emoji characters: ")
show_characters(emoji)
input("\n\nPress Enter to finish")
Important: First we define a function, and only then we call it in the main program.

9. Lists – storing multiple values

When we need to remember many elements (e.g. 5 numbers), instead of inventing variables like a0, a1, a2..., we use a list.

List definition

list_name = [element1, element2, ..., elementn]

Element indexes

a = [10, 20, 30, 40, 50]
print(a[0])   # 10
print(a[4])   # 50

Useful ways to create lists

MethodExampleMeaning
Typing values directly DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] A list of 12 elements (indexes 0–11)
The same value many times my_list = [0] * 10 A list of 10 zeros
Size stored in a variable N = 100\nmy_list = [0] * N A list of 100 elements

10. Exercise: enter data into a list and display it (functions + list)

Goal

Create a list a consisting of 5 integers, read them from the keyboard using the enter_data() function, and then print them using print_data().

Step 1: prepare the list (5 elements)

N = 5
a = [0] * N

Step 2: define the function that reads data

def enter_data():
    for i in range(N):
        a[i] = int(input("Enter a number: "))

Step 3: define the function that displays data

def print_data():
    for i in range(N):
        print(a[i])

Step 4: call the functions in the main program

enter_data()
print_data()
input("\n\nPress Enter to finish")
What is happening here?
  1. We create a list a with five slots.
  2. The for loop in enter_data() fills consecutive indexes a[0]a[4].
  3. The for loop in print_data() prints each element on a separate line.

11. Worth revising (control questions)

  1. What is a program’s source code?
  2. What does it mean that Python interprets a program?
  3. What is a variable and what does the assignment operator = mean?
  4. Why do you sometimes need to use int() or float() together with input()?
  5. What are the basic arithmetic operators and how does / differ from //?
  6. How does the if statement work and why is indentation required?
  7. What is iteration and what is the for loop used for?
  8. How does range() work (1, 2, and 3 arguments)?
  9. How does a function that returns a value differ from one that does not?
  10. What is a list and why is the first element’s index 0?