Programowanie w języku Python (zmienne • warunki • pętle • funkcje • listy)

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

1. Co to jest kod źródłowy i uruchamianie programu

Wskazówka: Jeśli uruchamiasz plik dwuklikiem i okno znika zbyt szybko, na końcu programu możesz dodać:
input("\nAby zakończyć, naciśnij Enter")
To zatrzyma okno do momentu wciśnięcia Enter.

2. Zmienne – przechowywanie danych w pamięci

Zmienna to nazwana część pamięci (komórka pamięci), w której komputer przechowuje wartość. Zmienna ma nazwę i aktualną wartość.

Krok 1: Nadanie wartości zmiennej

liczba = 23

Krok 2: Zmiana (nadpisanie) wartości

liczba = liczba + 1
print(liczba)
Ważne: Zapis liczba = liczba + 1 nie jest równaniem matematycznym. To polecenie: „weź obecną wartość zmiennej, dodaj 1 i zapisz wynik z powrotem do tej samej zmiennej”.

Typy danych (Python rozpoznaje je automatycznie)

TypCo przechowujePrzykład
intliczby całkowiterok = 2021
floatliczby rzeczywiste (z kropką)wzrost = 159.5
strtekst (ciąg znaków)nazwisko = "Kowalski"
Uwaga o zapisie liczb: w Pythonie część dziesiętną zapisujemy kropką, np. 34.5, a nie 34,5.

3. Wyświetlanie informacji – print()

Funkcja print() wyświetla tekst i wyniki obliczeń w konsoli.

suma = 10 + 5
print("Suma wynosi:", suma)

Znak nowej linii \n

4. Operatory arytmetyczne

OperatorDziałaniePrzykładCo otrzymasz
+dodawanie23 + 5679
-odejmowanie987 - 233754
*mnożenie432 * 62592
//dzielenie całkowite (ucina część ułamkową)55 // 318
/dzielenie „z ułamkiem”55 / 318.3333...
%reszta z dzielenia37 % 41

Uwaga: plus przy tekstach

Jeśli zmienne są tekstami (str), to + oznacza łączenie tekstów:

print("samo" + "chód")   # wynik: samochód

5. Wprowadzanie danych z klawiatury – input()

input() wyświetla komunikat i czeka, aż użytkownik wpisze dane. Zwraca zawsze tekst (typ str).

Krok 1: Wczytaj tekst

miasto = input("Wprowadź nazwę miasta: ")
print(miasto)

Krok 2: Wczytaj liczbę całkowitą

liczba = int(input("Wprowadź liczbę: "))

Krok 3: Wczytaj liczbę rzeczywistą

srednia = float(input("Podaj średnią ocen: "))
Dlaczego czasem wychodzą różne wyniki?
Jeśli zrobisz liczba = input(...), to liczba jest tekstem. Wtedy liczba + liczba to sklejanie (np. "34" + "34" → "3434").
Jeśli zrobisz liczba = int(input(...)), to liczba + liczba to dodawanie (34 + 34 → 68).

6. Instrukcja warunkowa – if / else

Instrukcja warunkowa pozwala programowi podjąć decyzję na podstawie warunku (prawda/fałsz).

Postać pełna (z else)

if warunek:
    lista_instrukcji1
else:
    lista_instrukcji2
kolejna_instrukcja

Postać uproszczona (bez else)

if warunek:
    lista_instrukcji1
kolejna_instrukcja
Wcięcia: Blok po if (i po else) musi być wcięty. Najczęściej stosuje się 4 spacje. Brak wcięcia = błąd składni.

Operatory porównania i logiczne

GrupaOperatorZnaczeniePrzykład
Porównania==równya == b
!=różnya != b
<mniejszya < b
>większya > b
>=większy lub równya >= b
<=mniejszy lub równya <= b
Logiczneorluba < -5 or a > 5
andia > 0 and a < 10
notnegacja (zaprzeczenie)not a == 5

Przykład 1: większa z dwóch liczb (ćwiczenie z warunkiem)

a = int(input("Podaj pierwszą liczbę: "))
b = int(input("Podaj drugą liczbę różną od pierwszej: "))

if a > b:
    print("Większa jest pierwsza liczba", a)
else:
    print("Większa jest druga liczba", b)

input("\n\nAby zakończyć, naciśnij Enter")

Przykład 2: liczba dodatnia czy niedodatnia

x = int(input("Podaj liczbę całkowitą: "))

if x > 0:
    print("Liczba dodatnia")
else:
    print("Liczba niedodatnia")

7. Iteracje – pętla for (powtarzanie czynności)

Iteracja to powtarzanie tej samej operacji. W Pythonie najczęściej używamy do tego pętli for.

Ogólna postać

for zmienna in lista_wartosci:
    lista_instrukcji

lista_wartosci może być prawdziwą listą (np. [0,1,2,3,4]) albo sekwencją wygenerowaną przez range().

for po „prawdziwej” liście

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

range() – najczęstszy generator liczb

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
Uwaga o końcu range(): liczba koniec nie wchodzi do sekwencji (zawsze kończymy na koniec-1).

Przykład: pięć prostokątów (wielokrotne liczenie pola)

for i in range(5):
    x = int(input("Podaj długość pierwszego boku: "))
    y = int(input("Podaj długość drugiego boku: "))
    pole = x * y
    print("Pole działki o boku", x, "i boku", y, "wynosi:", pole)

input("\n\nAby zakończyć, naciśnij Enter")

8. Funkcje – porządkowanie programu

Funkcja (podprogram) to wydzielony fragment kodu o jednoznacznej nazwie. Dzięki funkcjom łatwiej utrzymać porządek i wielokrotnie używać tego samego rozwiązania.

Definicja funkcji

def nazwa_funkcji(lista_parametrow):
    lista_instrukcji
    return wartosc

Funkcja zwracająca wartość (z return) – przykład: objętość sześcianu

def szescian(a):
    return a * a * a

bok = int(input("Podaj długość boku sześcianu: "))
print("Objętość sześcianu o boku długości", bok, "wynosi:", szescian(bok))
input("\n\nNaciśnij Enter, aby zakończyć")

Funkcja niezwracająca wartości (bez return) – przykład: „rysowanie” znaków

def pokaz_znaki(znaki):
    for i in range(1, 11):
        print(znaki * i)

emotikon = input("Wprowadź znaki emotikona: ")
pokaz_znaki(emotikon)
input("\n\nNaciśnij Enter, aby zakończyć")
Ważne: Najpierw definiujemy funkcję, a dopiero potem ją wywołujemy w programie głównym.

9. Listy – przechowywanie wielu wartości

Gdy potrzebujemy zapamiętać wiele elementów (np. 5 liczb), zamiast wymyślać zmienne a0, a1, a2..., używamy listy.

Definicja listy

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

Indeksy elementów

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

Przydatne sposoby tworzenia list

SposóbPrzykładCo oznacza
Wpisanie wartości od razu L_DNI_W_MIESIACU = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] Lista 12 elementów (indeksy 0–11)
Ta sama wartość wiele razy moja_lista = [0] * 10 Lista 10 zer
Rozmiar w zmiennej N = 100\nlista = [0] * N Lista 100 elementów

10. Ćwiczenie: wprowadzamy dane do listy i wyświetlamy je (funkcje + lista)

Cel

Utworzyć listę a złożoną z 5 liczb całkowitych, wczytać je z klawiatury funkcją wprowadz_dane(), a potem wypisać funkcją wyprowadz_dane().

Krok 1: przygotuj listę (5 elementów)

N = 5
a = [0] * N

Krok 2: zdefiniuj funkcję wprowadzającą dane

def wprowadz_dane():
    for i in range(N):
        a[i] = int(input("Podaj liczbę: "))

Krok 3: zdefiniuj funkcję wyświetlającą dane

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

Krok 4: wywołaj funkcje w programie głównym

wprowadz_dane()
wyprowadz_dane()
input("\n\nNaciśnij Enter, aby zakończyć")
Co tu się dzieje?
  1. Tworzymy listę a z pięcioma miejscami.
  2. Pętla for w wprowadz_dane() wypełnia kolejne indeksy a[0]a[4].
  3. Pętla for w wyprowadz_dane() wypisuje każdy element w osobnym wierszu.

11. Warto powtórzyć

  1. Czym jest kod źródłowy programu?
  2. Na czym polega interpretacja programu przez Pythona?
  3. Co to jest zmienna i co oznacza instrukcja przypisania =?
  4. Dlaczego czasem trzeba użyć int() lub float() razem z input()?
  5. Jakie są podstawowe operatory arytmetyczne i czym różni się / od //?
  6. Jak działa instrukcja if i dlaczego wcięcia są obowiązkowe?
  7. Czym jest iteracja i do czego służy pętla for?
  8. Jak działa range() (1, 2 i 3 argumenty)?
  9. Czym różni się funkcja zwracająca wartość od tej, która jej nie zwraca?
  10. Co to jest lista i dlaczego indeks pierwszego elementu to 0?

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

  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?