Python2019/labs02/Podstawy cz. 2.ipynb
2019-01-27 08:55:03 +01:00

8.6 KiB
Raw Blame History

Podstawy Pythona: cz. 3

 

27 stycznia 2019

Co już było?

  • podstawowe typy danych
  • operacje arytmetyczne
  • wyświtlanie na ekran
  • pętla for, instrukcja if
  • listy i słowniki

Funkcje

  • znamy kilka funkcji, np. print, len
  • funckje w pythonie nie odbiegają od funkcji w innych językach
  • może istnieć tylko 1 funkcja o danej nazwie
def nazwa_funkcji(argument1, argument2, argument3):
    # instrukcje do wykoniania
    return wartosc
def is_greater_than_5(x):
    if x > 5:
        return True
    else:
        return False
    
print(is_greater_than_5(10))
True
def srednia(lista):
    s = 0
    for item in lista:
        s += item
    return s / len(lista) 

print(srednia([7,8,9]))
8.0
def count(lista, item):
    l = 0
    for i in lista:
        if i == item:
            l += 1
    return l
count([3,3,3,4], 3)
count(lista=[3,3,3,4], item=3)
count(item=3, lista=[3,3,3,4])
3
def is_grater_than(x, y=0):
    if x > y:
        return True
    else:
        return False
is_grater_than(5)
is_grater_than(x=5)
is_grater_than(5, 0)
is_grater_than(5, 6)
False
def alfaRange(x, y):
    for i in range(ord(x), ord(y)):
        yield chr(i)
print(list(alfaRange('a', 'e')))
['a', 'b', 'c', 'd']

Operacje na plikach

plik = open("haslo.txt", 'r')
for linia in plik.readlines():
    print(linia.strip())
print(">>")
plik.close()
with open("haslo.txt", 'r') as plik:
    for linia in plik.readlines():
        print(linia)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-18-c98a6e23ed86> in <module>
----> 1 with open("haslo.txt", 'r') as plik:
      2     for linia in plik.readlines():
      3         print(linia)

FileNotFoundError: [Errno 2] No such file or directory: 'haslo.txt'
with open("haslo2.txt", 'w') as plik:
    for word in ('corect', 'horse', 'battery', 'staple'):
        plik.write(word)
    plik.write('\n')
with open("haslo2.txt", 'w+') as plik:
    plik.writelines([' '.join(('corect', 'horse', 'battery', 'staple'))])

Korzystanie z bibliotek

import os
print(os.name)

from os import getenv
print('Nazwa uzytkownika: {}'.format(getenv("USER")))
posix
Nazwa uzytkownika: tomasz
from collections import *
print(Counter("konstantynopolitańczykowianeczka"))

import numpy as np
np.array([[1, 3, 4, 5]], dtype='float32')
Counter({'o': 4, 'n': 4, 'a': 4, 'k': 3, 't': 3, 'y': 2, 'i': 2, 'c': 2, 'z': 2, 's': 1, 'p': 1, 'l': 1, 'ń': 1, 'w': 1, 'e': 1})
array([[1., 3., 4., 5.]], dtype=float32)