Obliczenia.py).input("\nAby zakończyć, naciśnij Enter")
To zatrzyma okno do momentu wciśnięcia Enter.
Zmienna to nazwana część pamięci (komórka pamięci), w której komputer przechowuje wartość. Zmienna ma nazwę i aktualną wartość.
liczba = 23
liczba = liczba + 1
print(liczba)
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”.
| Typ | Co przechowuje | Przykład |
|---|---|---|
int | liczby całkowite | rok = 2021 |
float | liczby rzeczywiste (z kropką) | wzrost = 159.5 |
str | tekst (ciąg znaków) | nazwisko = "Kowalski" |
34.5, a nie 34,5.
Funkcja print() wyświetla tekst i wyniki obliczeń w konsoli.
suma = 10 + 5
print("Suma wynosi:", suma)
\n\n oznacza przejście do nowego wiersza,\n\n oznacza dwa nowe wiersze (pusta linia między tekstami).| Operator | Działanie | Przykład | Co otrzymasz |
|---|---|---|---|
+ | dodawanie | 23 + 56 | 79 |
- | odejmowanie | 987 - 233 | 754 |
* | mnożenie | 432 * 6 | 2592 |
// | dzielenie całkowite (ucina część ułamkową) | 55 // 3 | 18 |
/ | dzielenie „z ułamkiem” | 55 / 3 | 18.3333... |
% | reszta z dzielenia | 37 % 4 | 1 |
Jeśli zmienne są tekstami (str), to + oznacza łączenie tekstów:
print("samo" + "chód") # wynik: samochód
input() wyświetla komunikat i czeka, aż użytkownik wpisze dane. Zwraca zawsze tekst (typ str).
miasto = input("Wprowadź nazwę miasta: ")
print(miasto)
liczba = int(input("Wprowadź liczbę: "))
srednia = float(input("Podaj średnią ocen: "))
liczba = input(...), to liczba jest tekstem. Wtedy liczba + liczba to sklejanie (np. "34" + "34" → "3434").liczba = int(input(...)), to liczba + liczba to dodawanie (34 + 34 → 68).
Instrukcja warunkowa pozwala programowi podjąć decyzję na podstawie warunku (prawda/fałsz).
if warunek:
lista_instrukcji1
else:
lista_instrukcji2
kolejna_instrukcja
if warunek:
lista_instrukcji1
kolejna_instrukcja
if (i po else) musi być wcięty. Najczęściej stosuje się 4 spacje. Brak wcięcia = błąd składni.
| Grupa | Operator | Znaczenie | Przykład |
|---|---|---|---|
| Porównania | == | równy | a == b |
!= | różny | a != b | |
< | mniejszy | a < b | |
> | większy | a > b | |
>= | większy lub równy | a >= b | |
<= | mniejszy lub równy | a <= b | |
| Logiczne | or | lub | a < -5 or a > 5 |
and | i | a > 0 and a < 10 | |
not | negacja (zaprzeczenie) | not a == 5 |
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")
x = int(input("Podaj liczbę całkowitą: "))
if x > 0:
print("Liczba dodatnia")
else:
print("Liczba niedodatnia")
Iteracja to powtarzanie tej samej operacji. W Pythonie najczęściej używamy do tego pętli for.
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 i in [0, 1, 2, 3, 4]:
print(i)
range(koniec) → 0, 1, 2, ..., koniec-1range(poczatek, koniec) → początek, ..., koniec-1range(poczatek, koniec, krok) → jak wyżej, ale „co krok”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
koniec nie wchodzi do sekwencji (zawsze kończymy na koniec-1).
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")
Funkcja (podprogram) to wydzielony fragment kodu o jednoznacznej nazwie. Dzięki funkcjom łatwiej utrzymać porządek i wielokrotnie używać tego samego rozwiązania.
def nazwa_funkcji(lista_parametrow):
lista_instrukcji
return wartosc
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ć")
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ć")
Gdy potrzebujemy zapamiętać wiele elementów (np. 5 liczb), zamiast wymyślać zmienne a0, a1, a2..., używamy listy.
nazwa_listy = [element1, element2, ..., elementn]
a = [10, 20, 30, 40, 50]
print(a[0]) # 10
print(a[4]) # 50
| Sposób | Przykład | Co 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 |
Utworzyć listę a złożoną z 5 liczb całkowitych, wczytać je z klawiatury funkcją wprowadz_dane(), a potem wypisać funkcją wyprowadz_dane().
N = 5
a = [0] * N
def wprowadz_dane():
for i in range(N):
a[i] = int(input("Podaj liczbę: "))
def wyprowadz_dane():
for i in range(N):
print(a[i])
wprowadz_dane()
wyprowadz_dane()
input("\n\nNaciśnij Enter, aby zakończyć")
a z pięcioma miejscami.for w wprowadz_dane() wypełnia kolejne indeksy a[0] … a[4].for w wyprowadz_dane() wypisuje każdy element w osobnym wierszu.=?int() lub float() razem z input()?/ od //?if i dlaczego wcięcia są obowiązkowe?for?range() (1, 2 i 3 argumenty)?Calculations.py).input("\nTo finish, press Enter")
This will keep the window open until you press Enter.
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.
number = 23
number = number + 1
print(number)
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”.
| Type | What it stores | Example |
|---|---|---|
int | integers | year = 2021 |
float | real numbers (with a dot) | height = 159.5 |
str | text (a string) | surname = "Kowalski" |
34.5, not 34,5.
The print() function displays text and calculation results in the console.
total = 10 + 5
print("The total is:", total)
\n\n means move to a new line,\n\n means two new lines (a blank line between texts).| Operator | Operation | Example | What you get |
|---|---|---|---|
+ | addition | 23 + 56 | 79 |
- | subtraction | 987 - 233 | 754 |
* | multiplication | 432 * 6 | 2592 |
// | integer division (cuts off the fractional part) | 55 // 3 | 18 |
/ | division “with a fraction” | 55 / 3 | 18.3333... |
% | remainder (modulo) | 37 % 4 | 1 |
If variables are strings (str), then + means concatenation (joining strings):
print("car" + "pet") # result: carpet
input() displays a prompt and waits until the user types something. It always returns text (type str).
city = input("Enter the name of a city: ")
print(city)
number = int(input("Enter a number: "))
average = float(input("Enter your grade average: "))
number = input(...), then number is a string. In that case number + number means concatenation (e.g. "34" + "34" → "3434").number = int(input(...)), then number + number means addition (34 + 34 → 68).
A conditional statement lets the program make a decision based on a condition (true/false).
if condition:
list_of_instructions1
else:
list_of_instructions2
next_instruction
if condition:
list_of_instructions1
next_instruction
if (and after else) must be indented. Most commonly we use 4 spaces. No indentation = syntax error.
| Group | Operator | Meaning | Example |
|---|---|---|---|
| Comparisons | == | equal | a == b |
!= | not equal | a != b | |
< | less than | a < b | |
> | greater than | a > b | |
>= | greater than or equal | a >= b | |
<= | less than or equal | a <= b | |
| Logical | or | or | a < -5 or a > 5 |
and | and | a > 0 and a < 10 | |
not | negation (NOT) | not a == 5 |
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")
x = int(input("Enter an integer: "))
if x > 0:
print("Positive number")
else:
print("Non‑positive number")
An iteration is repeating the same operation. In Python, we most often use the for loop for this.
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 i in [0, 1, 2, 3, 4]:
print(i)
range(end) → 0, 1, 2, ..., end-1range(start, end) → start, ..., end-1range(start, end, step) → same as above, but “every step”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
end is not included in the sequence (we always end at end-1).
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")
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.
def function_name(parameter_list):
list_of_instructions
return value
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")
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")
When we need to remember many elements (e.g. 5 numbers), instead of inventing variables like a0, a1, a2..., we use a list.
list_name = [element1, element2, ..., elementn]
a = [10, 20, 30, 40, 50]
print(a[0]) # 10
print(a[4]) # 50
| Method | Example | Meaning |
|---|---|---|
| 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 |
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().
N = 5
a = [0] * N
def enter_data():
for i in range(N):
a[i] = int(input("Enter a number: "))
def print_data():
for i in range(N):
print(a[i])
enter_data()
print_data()
input("\n\nPress Enter to finish")
a with five slots.for loop in enter_data() fills consecutive indexes a[0] … a[4].for loop in print_data() prints each element on a separate line.= mean?int() or float() together with input()?/ differ from //?if statement work and why is indentation required?for loop used for?range() work (1, 2, and 3 arguments)?