Improve your programming skills

Python tutorial – w3schools based

This is my learning log from w3schools python tutorial


Python HOME (todo)

todo

Python Intro

https://www.w3schools.com/python/python_intro.asp

# created by Guido van Rossum, and released in 1991
# used for: web development (server-side), software development, mathematics, system scripting.
# good to read about history and use

Python Get Started

https://www.w3schools.com/python/python_getstarted.asp

# check version on Linux and Windows. Need to be run form shell
# python --version

# run pythonfile. Need to be run from command line:
# python your_script.py

# run python from shell. Need to be run from command line:

# python
# or
# py

# after that you can write python language

# press CTRL+D to exit python or use type: exit()
# exit()

Python Syntax

https://www.w3schools.com/python/python_syntax.asp

# Indentation
# Refer to spaces at the beginning of the code
# use indentation to indicate block of code

if 5 == 5:
    print("OK")

# You will receive an error, when don't use right indentation
# example:
# if 5 == 5:
# print("OK")

# most common spaces is 4, but it can be also one
if 5 > 2:
 print("OK!")
if 5 > 2:
        print("OK!")

# You need to use the same number of spaces in one code block. Else you will receive an error msg.

# Variables:
# Variables are created when you assign a value to it
x = 2
y = "Some text"

# You can run print funtion for more than one arguments
print(x, y)

# This is a comment.

Python Comments

https://www.w3schools.com/python/python_comments.asp

# comment example

print(x) # comment example

"""
comment example
in more than
one line
"""

Python Variables

Python Variables

https://www.w3schools.com/python/python_variables.asp

# Creating Variables
x = 54
y = "Some text"
print(x,y)

# variable type can be changed while app running
y = 11.23
print(y)

# Casting
# If you want to specify the data type of a variable, this can be done with casting.

x = int(2)
y = str(3)
z = float(4)
print(x, y, z)

Variable names

https://www.w3schools.com/python/python_variables_names.asp

# Variable names

# python variables namig rules:
# start with letter or underscore character "_". Cannon start with a number
# can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
# case sensitive

myVar = "Some txt"
my_var = "123"
MYVAR = "Some text2"
_myvar = "Some exapmple"

# myVar and MYVAR are other variables

print(myVar, my_var, MYVAR, _myvar)

# illegal naming:
# 1my_var = "txt"
# my-_myvar = "txt"

Asigning multiple variables

https://www.w3schools.com/python/python_variables_multiple.asp

# Asigning multiple variables

x, y, z = 1, "OK", 1.23
print(x, z, y)

# One Value to multiple variables
x = y = z = "Text"
print(x, y, z)

# Unpack collecion

fruits = ["apple", "banana", "orange"]

x, y, z = fruits
print(fruits)
print(x, y, z)
print(x)
print(y)
print(z)

Output Variables

https://www.w3schools.com/python/python_variables_output.asp

# Output Variables

x = "Python "
y = "is "
z = "Awesome"
print(x, y, z)
print(x)
print(y)
print(z)

# concatenate
print(x + y + z)

# + sign for math
x = 12
y = 5
print(x + y)

# string and number cannot be concatenate:
# x = 12
# y = "some text"
# print(x + y)

# but
x = "12"
y = "some text"
print(x + y)

# or
x = "12"
y = 1
print(int(x) + y)

Global variables

https://www.w3schools.com/python/python_variables_global.asp

# Global variables

# variables outside function can be use inside the function
x = "test my function"

def my_function():
print(x)

my_function()

# variables outside function and same name variable inside the function

x = "text in var outside the function"

def my_funciton2():
x = "text in var inside the function"
print(x)

my_funciton2()
print(x)

# The global Keyword
# to create global variable, use the global keyword

def my_funciton3():
global x
x = "variable inside the function"
print(x)

my_funciton3()
print(x)

# use the global keyword if you want to change a global variable inside a function.
x = "text in var outside the function"

def my_funciton3():
global x
x = "text in var inside the function"
print(x)

print(x)
my_funciton3()
print(x)

Python Data Types

https://www.w3schools.com/python/python_datatypes.asp

# different types can do different things.
# Python has the following data types built-in by default, in these categories

# Text Type: str
# Numeric Types: int, float, complex
# Sequence Types: list, tuple, range
# Mapping Type: dict
# Set Types: set, frozenset
# Boolean Type: bool
# Binary Types: bytes, bytearray, memoryview
# None Type: NoneType

# use type() function to get data type of any object
x = "text"
print(type(x))

# setting datatype
x = "Hello World" # str
print(x, type(x))
x = 20 # int
print(x, type(x))
x = 20.5 # float
print(x), type(x)
x = 1j # complex
print(x, type(x))
x = ["apple", "banana", "cherry"] # list
print(x, type(x))
x = ("apple", "banana", "cherry") # tuple
print(x, type(x))
x = range(6) # range
print(x, type(x))
x = {"name" : "John", "age" : 36} # dict
print(x, type(x))
x = {"apple", "banana", "cherry"} # set
print(x, type(x))
x = frozenset({"apple", "banana", "cherry"}) # frozenset
print(x, type(x))
x = True # bool
print(x, type(x))
x = b"Hello" # bytes
print(x, type(x))
x = bytearray(5) # bytearray
print(x, type(x))
x = memoryview(bytes(5)) # memoryview
print(x, type(x))
x = None # NoneType
print(x, type(x))

# look at:
# range, bytearray, frozenset, bytes, memoryview


# Setting the Specific Data Type
# Functions to create specific datatype
# If you want to specify the data type, you can use the following constructor functions:
x = str("Hello World") # str
print(x, type(x))
x = int(20) # int
print(x, type(x))
x = float(20.5) # float
print(x, type(x))
x = complex(1j) # complex
print(x, type(x))
x = list(("apple", "banana", "cherry")) # list
print(x, type(x))
x = tuple(("apple", "banana", "cherry")) # tuple
print(x, type(x))
x = range(6) # range
print(x, type(x))
x = dict(name="John", age=36) # dict
print(x, type(x))
x = set(("apple", "banana", "cherry")) # set
print(x, type(x))
x = frozenset(("apple", "banana", "cherry")) # frozenset
print(x, type(x))
x = bool(5) # bool
print(x, type(x))
x = bytes(5) # bytes
print(x, type(x))
x = bytearray(5) # bytearray
print(x, type(x))
x = memoryview(bytes(5)) # memoryview
print(x, type(x))

Python Numbers

https://www.w3schools.com/python/python_numbers.asp

# 3 numeric datatypes in python
# int, float, complex

x = 1
y = .23 # 0 is not a need
z = 1j

print(x, y, z)

print(type(x))
print(type(y))
print(type(z))

# int - positive or negative, without decimals and with unlimitted length
x = -121323456789078675654345679809786756454345678
x = x * x
print(x)
print(type(x))

# float, positive or negative, containing one or more decimals.
x = 1.123
y = .23
z = 3.0 # float created
print(x, y, z)
print(type(x))
print(type(y))
print(type(z))

# float with e
y = 12E4
z = -87.7e100

x = 35e3
y = 12E4
z = -87.7e100
print(x, y, z)
print(type(x))
print(type(y))
print(type(z))

# Complex
# Complex numbers are written with a "j" as the imaginary part

x = 3+5j
y = 5j
z = -6j

print(type(x))
print(type(y))
print(type(z))

print(x + y + z)

# numbers conversion
# int(), float(), and complex() methods

x = 1 # int
y = 2.8 # float
z = 1j # complex
print(x, y, z)

a = float(x)
print("a: ", a)
b = int(y)
print("b: ", b)
c = complex(y)
print("c: ", c)

print(type(a))
print(type(b))
print(type(c))

# Random Number
# pseudo random numbers
# Python does not have a random() function to make a random number, but Python has a built-in module called random

import random
x = random.randrange(1, 10)
print(x)

Python Casting

https://www.w3schools.com/python/python_casting.asp

# Changing data type can be done by using casting
# int()
# float()
# str()

Python Strings

Python Strings

https://www.w3schools.com/python/python_strings.asp

# STRINGS
# Single and double quotes can be used to define string variable
print("Hello")
print('Hello')

# String sentence can be defined in more than one lines using tripple double-quotes

x = """This is text
that can be written
in more than one lines"""
print(x)

# single quotes can be also used
x = '''This is text
that can be written
in more than one lines'''
print(x)

# Strings in python are arrays of bytes, that represents unicode characters
# You can acces to any single element of string
print(x[0])
print(x[1])
print(x[2])

# text from the left site
print(x[-1])

# more than one characters using position number
print(x[2:15])

# more than one character from the left site
print(x[-15:-1])

# Looping to a string
# You can iterate single elements from string using loop
for x in "This is a text":
print(x)

# String length can be return using len() funtion
x = "This is a text"
print(len(x))

# You can check, that word or signs exist in some text
# Returns True/False
x = "This is a text"
print("is" in x)

# Combined with if statement

text = "This is a text"
if " q " in text:
print("Yes, it's true")
else:
print("No, it's False")

# You can also use not is insted is operator:
text = "This is a text"
if " q " not in text:
print("Yes, it's true")
else:
print("No, it's False")

Slicing Strings

https://www.w3schools.com/python/python_strings_slicing.asp

## Python - Slicing Strings

z = "This is a text to train slicing"
# getting string part - signle character
print(z[3])

# getting string part - more than on character
print(z[3:5])

# from the left all characters starting from 5
print(z[5:])

# from the left all characters to 10th character
print(z[:10])

# from the right single character
print(z[-1])
print(z[-7])

# from the right more than one character
print(z[-7:])

# from the right text part
print(z[-7:-3])

# all characters up to 7th from the right
print(z[:-7])

Modify strings

https://www.w3schools.com/python/python_strings_modify.asp

# Strings modify

# Lowercase and uppercase
# use build in method in python
x = " I like learning Python "
print(x.upper())
print(x.lower())

# removing whitespaces from the end and from the beggining
print(x.strip())

# replacing part of text or a single sign
x = "I like learning Python"
print(x.replace("learning", "writing code in"))

# Split strings
# Create list from string
# type separator character ie: comma ","
x = "I like learning, Python"
print(x.split(","))

Concatenate strings

https://www.w3schools.com/python/python_strings_concatenate.asp

# concatenate strings
x = "I "
y = "like "
z = "Python"

print(x, y, z)
print(x+y+z)

a = "I like"
b = "coding"
c = a + b
print(c) # returns string without space

# Yuo can add space character
print(a + " " + b)

Format strings

https://www.w3schools.com/python/python_strings_format.asp

# Format strings

# You cannot con cacatenate strings and numbers:
age = 29
txt = "Your age is: "
# print(txt + age)

# Strings and numbers can combine using format methods
age = 29
txt = "Your age is: {}"

print(txt.format(age))

# there are no limit of arguments using format method
bananas = 5
price = 40
txt = "You have bought {} bananas for {} dollars."
z = txt.format(bananas, price)
print(z)

# values can be ordered
# there are no limit of arguments using format method
price = 40
bananas = 5
txt = "You have bought {0} bananas for {1} dollars."
z = txt.format(bananas, price)
print(z)

Escape characters

https://www.w3schools.com/python/python_strings_escape.asp

# Python - Escape Characters and other illegal characters and special values
# escape character is used for illegal characters ie: ""
# escape character allows double quotes, when text is written using double quotes

x = " This is a \"simple\" text"
print(x)
# \" < excape character

# tk: single quotes example"
x = 'This is a \'simple\' text'
print(x)

# \' Single Quote
# \\ Backslash
# \n New Line
# \r Carriage Return
# \t Tab
# \b Backspace
# \f Form Feed
# \ooo Octal value
# \xhh Hex value

String methods

https://www.w3schools.com/python/python_strings_methods.asp

# string methods
txt = "this is a sentence. "
# capitalize - first letter are uppercase
print(txt.capitalize())

txt = "This is a sentence. "
# casefold - Converts string into lower case
# This method is similar to the lower() method, but the casefold() method is stronger, more aggressive,
# meaning that it will convert more characters into lower case,
# and will find more matches when comparing two strings and both are converted using the casefold() method.
print(txt.casefold())

# center() Returns a centered string
# require length of output string
# there can be also deefines signs before and after
txt = "banana"
x = txt.center(20, "O")
print(x)
x = txt.center(20)
print(x)

# count() Returns the number of times a specified value occurs in a string
txt = "This is a sentence. "
print(txt.count("i")) # i letter <TK
print(txt.count(" ")) # spaces <TK

# encode - Returns an encoded version of the string. Default utf-8 if no defined
txt = "Bolesławiec"
print(txt)
print(txt.encode(encoding="ascii", errors="backslashreplace"))
print(txt.encode(encoding="ascii", errors="ignore"))
print(txt.encode(encoding="ascii", errors="namereplace"))
print(txt.encode(encoding="ascii", errors="replace"))
print(txt.encode(encoding="ascii", errors="xmlcharrefreplace"))

# endswith() - Returns true if the string ends with the specified value

txt = "Uczę się programować w python"
print(txt.endswith("ć w python")) # returns true/false

txt = "Hello, welcome to my world."
x = txt.endswith("my world.", 5, 11) # Check if position 5 to 11 ends with the phrase "my world.":
print(x)
# false

# expandtabs() Sets the tab size of the string
# The expandtabs() method sets the tab size to the specified number of whitespaces.
# tk: expand whitespaces \t <tab key
txt = "H\te\tl\tl\to"

print(txt)
print(txt.expandtabs())
print(txt.expandtabs(2))
print(txt.expandtabs(4))
print(txt.expandtabs(10))


# find() Searches the string for a specified value and returns the position of where it was found
# tk: numeration from 0 of course
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)

# format() Formats specified values in a string
# todo: once a day!

# format_map() Formats specified values in a string
# todo: once a day!

# index() Searches the string for a specified value and returns the position of where it was found

# isalnum() Returns True if all characters in the string are alphanumeric
# isalpha() Returns True if all characters in the string are in the alphabet
# isdecimal() Returns True if all characters in the string are decimals
# isdigit() Returns True if all characters in the string are digits
# isidentifier() Returns True if the string is an identifier
# islower() Returns True if all characters in the string are lower case
# isnumeric() Returns True if all characters in the string are numeric
# isprintable() Returns True if all characters in the string are printable
# isspace() Returns True if all characters in the string are whitespaces
# istitle() Returns True if the string follows the rules of a title
# isupper() Returns True if all characters in the string are upper case
# join() Joins the elements of an iterable to the end of the string
# ljust() Returns a left justified version of the string
# lower() Converts a string into lower case
x = "ZDFZGSDX"
print(x.lower())

# lstrip() Returns a left trim version of the string
# maketrans() Returns a translation table to be used in translations
# partition() Returns a tuple where the string is parted into three parts
# replace() Returns a string where a specified value is replaced with a specified value
# rfind() Searches the string for a specified value and returns the last position of where it was found
# rindex() Searches the string for a specified value and returns the last position of where it was found
# rjust() Returns a right justified version of the string
# rpartition() Returns a tuple where the string is parted into three parts
# rsplit() Splits the string at the specified separator, and returns a list
# rstrip() Returns a right trim version of the string
# split() Splits the string at the specified separator, and returns a list
# splitlines() Splits the string at line breaks and returns a list
# startswith() Returns true if the string starts with the specified value
# strip() Returns a trimmed version of the string
# swapcase() Swaps cases, lower case becomes upper case and vice versa
# title() Converts the first character of each word to upper case
# translate() Returns a translated string
# upper() Converts a string into upper case
x = "erdfhgj"
print(x.upper())
# zfill() Fills the string with a specified number of 0 values at the beginning

String Excercises (todo)


Python Booleans

https://www.w3schools.com/python/python_booleans.asp

# Python booleans
# True/False

print(1==0)
print(9==9)
print(3223>1)


# if statement based od bool
if 1 == 9:
print("ok")
# The bool() function allows you to evaluate any value, and give you True or False in return,

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Python Operators

https://www.w3schools.com/python/python_operators.asp

# Python operators
## Arithmetic:
# + - * /
# % modulus
x=7
y=5
print(x % y) # rest from division

# exponentiation (POWER)
print(x ** y)

# floor division (without rest)
print(x // y)

## Assigment. Used to assign values to variables
print("Assigment:")
x=50
print(x)

x+=3
print(x)

x-=3
print(x)

x*=3
print(x)

x/=3
print(x)

x%=3
print(x)

x**=3
print(x)

x=3

x&=3
print(x)

x|=3
print(x)

x^=3
print(x)

x>>=3
print(x)

x<<=3
print(x)

## Comparison Operators
# returns true/false
print(x==y)

print(x!=y)

print(x>y)

print(x<y)

print(x<=y)

print(x>=y)

## Python Logical Operators
# returns true/fals
print(x>y and y==55) # true if both statements are true

print(x>y or y==12) # true if one of statements are true

print(not(x>y and y==x)) # true if result is false

## Membership Operators
# in / not in
x = 2
y = 6
z = [1, 2, 3, 4]

print(x in z)
print(y in z)

print(x not in z)
print(y not in z)


## Python Bitwise Operators
# Bitwise operators are used to compare (binary) numbers
print("Python Bitwise Operators")
# todo: chceck how to use
# used to check if a sequence is presented in an object
# & AND Sets each bit to 1 if both bits are 1
# | OR Sets each bit to 1 if one of two bits is 1
# ^ XOR Sets each bit to 1 if only one of two bits is 1
# ~ NOT Inverts all the bits
# << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
# >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off


Python Lists (todo)


Python Tuples (todo)


Python Sets (todo)


Python Dictionaries (todo)


Python If…Else (todo)


Python While Loops (todo)


Python For Loops (todo)


Python Functions

# Python Functions
# function - block of code that returns when its called
# data can be a result of function
# data can be function params


## Creating function
# def syntax

def myfunction():
print("This is function output")

## function calling
# call:
myfunction()

## Arguments
# You can add as many arguments as you want, just separate them with a comma.

def myfunction(fname):
print(fname, " is learning Python ")

myfunction("Tom")
myfunction("Ann")
# Arguments are often shortened to args in Python documentations.
# args = params
# The terms parameter and argument can be used for the same thing: information that are passed into a function.
# A parameter is the variable listed inside the parentheses in the function definition.
# An argument is the value that is sent to the function when it is called.

## Number of Arguments
# By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

def myfunction(name1, name2):
print(name1, "is learning Python and", name2, "also")

# myfunction("Tom", "Ann","aesfd") # generates error
myfunction("Tom", "Ann") # correct

## Arbitrary Arguments, *args
# If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
# Arbitrary Arguments are often shortened to *args in Python documentations.

def myfunction2(*args):
print("The best python course is:" + args[1])

myfunction2("w3schools", "tutorialspoint")

## Keyword Arguments
# You can also send arguments with the key = value syntax.
# This way the order of the arguments does not matter.
def my_function(person3, person2, person1):
print("The youngest is " + person3)

my_function(person1 = "Emil", person2 = "Tobias", person3 = "Linus")

# The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

## Arbitrary Keyword Arguments, **kwargs
# If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
# This way the function will receive a dictionary of arguments, and can access the items:
# If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")
# tk: two arg was given, but only one argument was needed

## Default Parameter Value
# The following example shows how to use a default parameter value.
# If we call the function without argument, it uses the default value:

def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

## Passing a List as an Argument
# You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
# E.g. if you send a List as an argument, it will still be a List when it reaches the function:

def my_function(food):
for x in food:
print(x) # print only list elements
print(food) # print as a list

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

## Return Values
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

## The pass Statement
# function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

def myfunction():
pass

myfunction()

## Recursion
# Python also accepts function recursion, which means a defined function can call itself.
# The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
# In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
# To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")
tri_recursion(6)


Python Lambda (todo)


Python Arrays (todo)


Python Classes/Objects

https://www.w3schools.com/python/python_classes.asp

# Python Classes and Objects
# Python is an object oriented programming language.
# Almost everything in Python is an object, with its properties and methods.
# A Class is like an object constructor, or a "blueprint" for creating objects.

## create a class
# Create Object
# To create a class, use the keyword class:
class myclass:
x = 5
y = 2
z = "some text"

# Now we can use the class named MyClass to create objects:

p1 = myclass()
print(p1.x)
print(p1.y)
print(p1.z)

## The __init__() Function
# The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
# To understand the meaning of classes we have to understand the built-in __init__() function. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# All classes have a function called __init__(), which is always executed when the class is being initiated.
# Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

# Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
# Note: The __init__() function is called automatically every time the class is being used to create a new object.

## The __str__() Function

# The __str__() function controls what should be returned when the class object is represented as a string.
# If the __str__() function is not set, the string representation of the object is returned:
# The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1)
print(p1.name)
print(p1.age)

# The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

## Object Methods
# Objects can also contain methods. Methods in objects are functions that belong to the object.

# Insert a function that prints a greeting, and execute it on the p1 object:
# tk: w klasach mogą być także funkcje (wczesniej zmienne)

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

# Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
# It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:

# Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is ......" + abc.name)

p1 = Person("John", 36)
p1.myfunc()

## Modify Object Properties
# modyfying object properties

p1.age=40
print(p1)
print(p1.age)

## Delete Object Properties
del p1.age
print(p1)
# print(p1.age) will give error

## The pass Statement
# class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

class Person:
pass

p1 = Person()
print(p1)

Python Inheritance

https://www.w3schools.com/python/python_inheritance.asp

## Python Inheritance

# Inheritance allows us to define a class that inherits all the methods and properties from another class.
# Parent class is the class being inherited from, also called base class.
# Child class is the class that inherits from another class, also called derived class.

## Create a Parent Class
# Any class can be a parent class, so the syntax is the same as creating any other class:

class person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

# Use the Person class to create an object, and then execute the printname method:
x = person("John", "Doe")
print(x)
x.printname()

## Create a Child Class
# Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
class student(person):
pass

x=student("Robert", "Kubica")
x.printname()

## Add the __init__() Function
# Add the __init__() function to the Student class:
# When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
# To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
# class student(person):
# def __init__(self, fname, lname):
# properties here

class student(person):
def __init__(self, fname, lname):
person.__init__(self, fname, lname)
# Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function.

## Use the super() Function
# Python also has a super() function that will make the child class inherit all the methods and properties from its parent:

class student(person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
# By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

## Add Properties

class student(person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
# In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function:

# Add a year parameter, and pass the correct year when creating objects:

class student(person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = student("Mike", "Olsen", 2019)

print(x)
print(x.graduationyear)

## Add Methods
# Add a method called welcome to the Student class:

class student(person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome, ", self.firstname , self.lastname)

x = student("Mike", "Olsen", 2019)
x.welcome()

# If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Python Iterators

https://www.w3schools.com/python/python_iterators.asp

## python iterators
# iterator is an object that contains a countable number of values
# Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

## Iterator vs Iterable
# Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
# All these objects have a iter() method which is used to get an iterator

mytupple = ("USA", "Poland", "Germany")
myit = iter(mytupple)

print(myit) # returns <tuple_iterator object at 0x000001C1E0188FA0>
print(type(myit)) # returns <class 'tuple_iterator'>

print(next(myit))
print(next(myit))
print(next(myit))

# Even strings are iterable objects, and can return an iterator:


mystr = "This is sentence"
myit=iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
# (...)

## Looping Through an Iterator

mytupple = ("USA", "Poland", "Germany")

for x in mytupple:
print(x)

mystr = "This is sentence"

for x in mystr:
print(x)
# The for loop actually creates an iterator object and executes the next() method for each loop.
# token: czy to wczesniejsze to czaqsem nie jest "jawne użycie iteratora?

## Create an Iterator
# To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.
# As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created.
# The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
# The __next__() method also allows you to do operations, and must return the next item in the sequence.

# Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
print("next excersize")

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

## StopIteration
# The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
# To prevent the iteration to go on forever, we can use the StopIteration statement.
# In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
# Stop after 20 iterations:

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)


Python Scope (todo)


Python Modules (todo)


Python Dates (todo)


Python Math (todo)


Python JSON

https://www.w3schools.com/python/python_json.asp

# Python JSON
# JavaScript Object Notation. It is syntax for storing and exchanging data
# JSON is a build-in package



## parse json is convert JSON to python DICTIONARY

import json

### example
json_example = '{"car": "BMW", "model": "series 3", "engine": 3.0}'

### parse json:
x = json.loads(json_example)
### see, that results previous written with double quotes has output with single quotes
print(x)

print(x["model"])

## Convert from Python to JSON
# see, that there are no quotes before {} and after {}
# this is simple dictionary
x = {"car": "BMW", "model": "series 3", "engine": 3.0}
print(x["car"])

### conversion: python dict to json

y=json.dumps(x)

print(y)
print(type(y))
### see, that is type str, so it is no longer dictionary. It is json string

# Other JSON convertsions
## following can be converted into JSON string:
# dict
# list
# tuple
# string
# int
# float
# True
# False
# None

# json python equivalents:
# Python JSON
# dict Object
# list Array
# tuple Array
# str String
# int Number
# float Number
# True true
# False false
# None null


# test (not my)
print(json.dumps({'name': 'John', 'age': 30})) # dict
print(json.dumps(["apple", "bananas"])) # list
print(json.dumps(("apple", "bananas"))) # tupple
print(json.dumps("hello")) # str
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

# complex python object. Containging other data types

x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

print(json.dumps(x))

# token: let see if we have json listed upper in string.
# it is work on a dict with complex data stored in a list
a = json.dumps(x)
print(a)
print(type(a))
b = json.loads(a)
print(b)
print(type(b))

print(b["name"])

print(b["children"])
# single item from array
print(b["children"][0])

print(b["cars"])
print(b["cars"][0])

print(b["cars"][0]["model"])
print(b["cars"][0]["mpg"])

# tk: great!

## Format the Result
c = json.dumps(x, indent=4)
print(c)

### You can also define the separators, default value is (", ", ": "),

d = json.dumps(x, indent=4, separators=(". ", " = "))
print(type(d))
print(d)

## Order the Result
### bellow is order by name. - alphabetical
e = json.dumps(x, indent=4, sort_keys=True)
print(e)

Python RegEx

https://www.w3schools.com/python/python_regex.asp

# Python regex
# Regular Expresssion - sequence of characters forms pattern
## build in package "re". It is regEx module
import re


## RegEx in Python

# my example
t = "I like learning Python"
x = re.search("^I like.*Python$", t)
print(x)

# from w3
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print(x)

## functions in regex module
#findall Returns a list containing all matches
#search Returns a Match object if there is a match anywhere in the string
#split Returns a list where the string has been split at each match
#sub Replaces one or many matches with a string

## Metacharacters in regex

# [] A set of characters "[a-m]"
# \ Signals a special sequence (can also be used to escape special characters) "\d"
# . Any character (except newline character) "he..o"
# ^ Starts with "^hello"
# $ Ends with "planet$"
# * Zero or more occurrences "he.*o"
# + One or more occurrences "he.+o"
# ? Zero or one occurrences "he.?o"
# {} Exactly the specified number of occurrences "he.{2}o"
# | Either or "falls|stays"
# () Capture and group

# Special Sequences
# A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:

# \A Returns a match if the specified characters are at the beginning of the string "\AThe"
# \b Returns a match where the specified characters are at the beginning or at the end of a word
# (the "r" in the beginning is making sure that the string is being treated as a "raw string") r"\bain"
# r"ain\b"
# \B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word
# (the "r" in the beginning is making sure that the string is being treated as a "raw string") r"\Bain"
# r"ain\B"
# \d Returns a match where the string contains digits (numbers from 0-9) "\d"
# \D Returns a match where the string DOES NOT contain digits "\D"
# \s Returns a match where the string contains a white space character "\s"
# \S Returns a match where the string DOES NOT contain a white space character "\S"
# \w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w"
# \W Returns a match where the string DOES NOT contain any word characters "\W"
# \Z Returns a match if the specified characters are at the end of the string "Spain\Z"

# Sets
# A set is a set of characters inside a pair of square brackets [] with a special meaning:

# [arn] Returns a match where one of the specified characters (a, r, or n) is present
# [a-n] Returns a match for any lower case character, alphabetically between a and n
# [^arn] Returns a match for any character EXCEPT a, r, and n
# [0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
# [0-9] Returns a match for any digit between 0 and 9
# [0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
# [a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
# [+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string

## The findall() Function

# my example
t = "I like learning Python and I hear you"
x = re.findall("ear", t)
print(x)
# returns two lists
print(type(x))

# If no matches are found, an empty list is returned
t = "I like learning Python and I hear you"
x = re.findall("xyz", t)
print(x)

## The search() Function
# my example
t = "I like learning Python and I hear you"
x = re.search("\s", t)
print(x)
# tk: \s Returns a match where the string contains a white space character "\s"

# my example
t = "I like learning Python and I hear you"
x = re.search("Python", t)
print(x)

## The split() Function
# The split() function returns a list where the string has been split at each match:
# my example
t = "I like learning Python and I hear you"
x = re.split("\s", t)
print(x)
# returns list of words: ['I', 'like', 'learning', 'Python', 'and', 'I', 'hear', 'you']

# You can control the number of occurrences by specifying the maxsplit parameter:

t = "I like learning Python and I hear you"
x = re.split("\s", t, 1)
print(x)
# returns list with two elements: ['I', 'like learning Python and I hear you']

# tk: or three
x = re.split("\s", t, 3)
print(x)
# returns list with two elements: ['I', 'like learning Python and I hear you']

## The sub() Function
# tk:
x = re.sub("\s", "99", t)
print(x)
# replace \s (whiote space with char :" I99like99learning99Python99and99I99hear99you

# You can control the number of replacements by specifying the count parameter:

x = re.sub("\s", "9", t, 2)
print(x)
# tk: first two occurences # I9like9learning Python and I hear you

## Match Object
# Note: If there is no match, the value None will be returned, instead of the Match Object.

x = re.search("ea", t)
print(x)
# this will print an object

# The Match object has properties and methods used to retrieve information about the search, and the result:
# .span() returns a tuple containing the start-, and end positions of the match.
# .string returns the string passed into the function
# .group() returns the part of the string where there was a match


# Print the position (start- and end-position) of the first match occurrence.

x = re.search(r"\bP\w+", t)
print(x.span())
# The regular expression looks for any words that starts with an upper case "P":
# returns: (16, 22)


# Print the string passed into the function:
x = re.search(r"\bP\w+", t)
print(x.string)


# Print the part of the string where there was a match.
# The regular expression looks for any words that starts with an upper case "P":

x = re.search(r"\bP\w+", t)
print(x.group())

Python PIP

https://www.w3schools.com/python/python_pip.asp

# PIP https://www.w3schools.com/python/python_pip.asp
# pip is a package manager
# from 3.4 pip is inculuded as default


# what is package": package oinclude all files you need for a module
# modules are code libraries

## Check if PIP is Installed
# on windows or linux
# pip -- version # from commmand line


## Install PIP
# If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/

## download package:
# pip install PACKAGE_NAME

## using package:
# import PACKAGENAME


## Find Packages
# Find more packages at https://pypi.org/.

## Remove a Package
# pip uninstall PACKAGENAME

## list packages and versions
# pip list


Python Try…Except (todo)


Python User Input

https://www.w3schools.com/python/python_user_input.asp

# Python user input
username = input("Enter username:")
print("Username is: " + username)

Python String Formatting (todo)

Leave a comment

Your email address will not be published. Required fields are marked *