Podstawy Programowania

Czym jest program

Algorytm

Implementacja

Testowanie

Zmienne

Liczbowe

>>> a = 5
>>> type(a)
<class 'int'>
>>> b = 5.5
>>> type(b)
<class 'float'>

Tekstowe

>>> c = "Tekst"
>>> type(c)
<class 'str'>

Tablice / Listy

>>> d = [5, 5.5, "Tekst"]
>>> type(d)
<class 'list'>
>>> d[0]
5
>>> d[1]
5.5
>>> d[2]
'Tekst'

*Struktury/Słowniki

>>> e = {'klucz': 'wartość', 'inny_klucz': 5}
>>> type(e)
<class 'dict'>
>>> e['klucz']
'wartość'
>>> e['inny_klucz']
5

I wiele innych...

Operacje na zmiennych

Liczbowe

Standardowe operacje:

+, -, /, *

Operacja potęgowania:

** (w niektórych językach - ^)

>>> 3 ^ 2
1
>>> 3 ** 2
9

Liczbowe cd.

Dzielenie całkowite

Reszta z dzielenia

>>> 5 % 2
1
>>> 5 // 2
2

Tekstowe

Łączenie tekstów

Wstawianie zmiennych do tekstu

>>> "Są {} pory roku".format(4)
'Są 4 pory roku'
>>> "Tom" + "asz"
'Tomasz'

Operacje logiczne

Operatory porównania

>, >=, ==, <=, <

>>> 2 > 2
False
>>> 2 >= 2
True
>>> 2 == 2
True
>>> 2 <= 2
True
>>> 2 < 2
False

Łączenie warunków

and, or

>>> 2 == 2 and 2 < 2
False
>>> 2 == 2 or 2 < 2
True

Sprawdzenie tablicy

>>> 5 in [1, "tekst", 5, 3]
True
>>> "tekst" in [1, "tekst", 5, 3]
True
>>> 2 in [1, "tekst", 5, 3]
False

Komunikacja

wejście

>>> f = input('Podaj f: ')
Podaj f: 3
>>> f
'3'

wyjście

>>> print('Hello')
Hello
>>> print('Twoja liczba to {}'.format(f))
Twoja liczba to 3

rzutowanie

>>> type(f)
<class 'str'>
>>> g = int(f)
>>> g
3
>>> type(g)
<class 'int'>
>>> f + g
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> int(f) + g
6
>>> f + str(g)
'33'

Instrukcje warunkowe

If

>>> if 2 == 2:
...     print('Równe')
... 
Równe
>>> if 2 > 2:
...     print('Większe')
...
>>> if 1 in [0, 1, 2, 3]:
...     print('Zawiera')
... 
Zawiera

If-else

>>> if 2 == 2:
...     print('Równe')
... else:
...     print('Różne')
... 
Równe
>>> if 2 == 3:
...     print('Równe')
... else:
...     print('Różne')
... 
Różne

If-elif-else

>>> if 2 == 3:
...     print('Równe')
... elif 2 < 3:
...     print('Mniejsze')
... else:
...     print('Większe')
... 
Mniejsze

Pętle

While

>>> i = 0
>>> while i < 10:
...     print(i)
...     i = i + 1
... 
0
1
2
3
4
5
6
7
8
9

For

>>> for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
...     print(i)
... 
0
1
2
3
4
5
6
7
8
9
>>> for i in range(10):
...     print(i)
... 
0
1
2
3
4
5
6
7
8
9

Kalkulator

Algorytm

  • Pobierz liczbę 1
  • Pobierz znak
  • Pobierz liczbę 2
  • Wykonaj działanie
  • Wyświetl wynik

Implementacja

a = input('A: ')
op = input('Znak: ')
b = input('B: ')

a = int(a)
b = int(b)

if op == '+':
    print('Wynik: {}'.format(a+b))

Testowanie

$ python program.py 
A: 1
Znak: +
B: 3
Wynik: 4

TODO:

  • Odejmowanie
  • Mnożenie
  • Dzielenie
  • Potęgowanie
  • *Dzielenie przez 0
  • *Niewłaściwy znak
  • *Niewłaściwa liczba

https://repl.it/classroom/invite/NwX1zmU

Funkcje

>>> def present_yourself():
...     print("Hi! I'm a program!")
... 
>>> present_yourself()
Hi! I'm a program!
>>> present_yourself()
Hi! I'm a program!

Podstawowa definicja

>>> def greet_user(user):
...     print(f"Hi {user}! Nice to meet you!")
... 

>>> some_user = input('Your username: ')
Your username: Łukasz
>>> greet_user(some_user)
Hi Łukasz! Nice to meet you!


>>> some_other_user = input('Your other username: ')
Your other username: VanDavv
>>> greet_user(some_other_user)
Hi VanDavv! Nice to meet you!

Parametry

>>> def suma(a, b):
...     return a + b
... 
>>> suma(1, 3)
4
>>> wynik = suma(2, 5)
>>> wynik
7

Zwracanie wyniku

Nie modyfikujcie parametrów!

przepraszam że po polsku :)

>>> suma = lambda a, b: a + b
>>> suma(1, 3)
4

Krótsza forma - lambda

>>> def suma(a, b):
...     return a + b
... 
>>> roznica = lambda a, b: a - b


>>> def calculate(func, a, b):
...     result = func(a, b)
...     print(result)
... 


>>> calculate(suma, 1, 3)
4
>>> calculate(roznica, 1, 3)
-2

Funkcje jako parametry

>>> operations = {
...     '+': lambda a, b: a + b,
...     '-': lambda a, b: a - b,
...     '*': lambda a, b: a * b,
...     '/': lambda a, b: a / b,
...     '**': lambda a, b: a ** b,
... }

>>> operation = operations[input('Działanie: ')]
Działanie: -

>>> print("Wynik: {}".format(operation(int(input('A: ')), int(input('B: ')))))
A: 2
B: 10
Wynik: -8

Kalkulator - fancy way (TODO)

I o tym dlaczego tak nie robić ;)

Wyjątki

Najlepszy i najgorszy towarzysz

Najlepsze - obsłużone

Najgorsze - niespodziewane

Kalkulator - fancy fail

>>> operations = {
...     '+': lambda a, b: a + b,
...     '-': lambda a, b: a - b,
...     '*': lambda a, b: a * b,
...     '/': lambda a, b: a / b,
...     '**': lambda a, b: a ** b,
... }

>>> operation = operations[input('Działanie: ')]
Działanie: podziel

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'podziel'

Kalkulator - poprawiamy

>>> operations = {
...     '+': lambda a, b: a + b,
...     '-': lambda a, b: a - b,
...     '*': lambda a, b: a * b,
...     '/': lambda a, b: a / b,
...     '**': lambda a, b: a ** b,
... }

>>> try:
...     operation = operations[input('Działanie: ')]
... except KeyError:
...     print(f"Błąd, niedozwolone działanie! Dostępne: {','.join(operations.keys())}")
... 
Działanie: podziel
Błąd, niedozwolone działanie! Dostępne: +,-,*,/,**

Kalkulator - fancy fail v2

>>> operations = {
...     '+': lambda a, b: a + b,
...     '-': lambda a, b: a - b,
...     '*': lambda a, b: a * b,
...     '/': lambda a, b: a / b,
...     '**': lambda a, b: a ** b,
... }

>>> try:
...     operation = operations[input('Działanie: ')]
... except KeyError:
...     print(f"Błąd, niedozwolone działanie! Dostępne: {','.join(operations.keys())}")
... 
Działanie: /

>>> print("Wynik: {}".format(operation(int(input('A: ')), int(input('B: ')))))
A: 10
B: 0

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in <lambda>
ZeroDivisionError: division by zero

Kalkulator - naprawiamy v2

>>> operations = {
...     '+': lambda a, b: a + b,
...     '-': lambda a, b: a - b,
...     '*': lambda a, b: a * b,
...     '/': lambda a, b: a / b,
...     '**': lambda a, b: a ** b,
... }

>>> try:
...     operation = operations[input('Działanie: ')]
... except KeyError:
...     print(f"Błąd, niedozwolone działanie! Dostępne: {','.join(operations.keys())}")
... 
Działanie: /

>>> try:
...     print("Wynik: {}".format(operation(int(input('A: ')), int(input('B: ')))))
... except ZeroDivisionError:
...     print("Nieładnie dzielić przez 0!")
... 
A: 10
B: 0
Nieładnie dzielić przez 0!

Dlaczego tak nie piszemy?

Jakie są wady i zalety takiego kodu?

Porozmawiajmy o stylu

W czym wy piszecie?

Co to jest IDE

Gdzie pisać kod

Konsola vs Notatnik vs IDE

Używanie wielu plików

Dzielenie kodu na moduły

greetings.py

def eng():
    print("Hello!")

def eng_custom(name):
    print("Hello {}!".format(name))

def pl():
    print("Cześć!")

def pl_custom(name):
    print("Cześć {}!".format(name))

main.py

import greetings

name = input("Name: ")
greetings.eng()
greetings.pl_custom(name)

Gdy coś nie działa - PYTHONPATH lub relative import

PYTHONPATH=. python main.py
import .greetings

Zmienna __name__

def eng():
    print("Hello!")

def eng_custom(name):
    print("Hello {}!".format(name))

def pl():
    print("Cześć!")

def pl_custom(name):
    print("Cześć {}!".format(name))
    
if __name__ == "__main__":
    print("Running directly, not by import!")
else:
    print("Being imported!")
$ python main.py 
Being imported!
Name: test
Hello!
Cześć test!

$ python greetings.py 
Running directly, not by import!

Git - podstawowe komendy

git init

git add <filename>

git commit -m "<message>"

git remote add origin <url>

git push

git reset --hard

git clone

Projekt

Odwzoruj działanie polecenia - cat

  • Pliku nie ma
  • Nie mamy uprawnień do pliku
  • -n, --number: number all output lines
  • -s, --squeeze-blank: suppress repeated empty output lines
  • -E, --show-ends: display $ at end of each line

Projekt 2

Command line tool do wysyłania emaili

Przykładowa składnia

python script.py <adresat> <temat> <treść>

 

Przykładowe użycie

python script.py lpilatowski@teonite.com TEST "To jest wiadomość"

Po wykonaniu skryptu mail powinien pojawić się na skrzynce

Podstawy Programowania

By vandavv

Podstawy Programowania

  • 505