Learning Python

Loops

While loop

def main():
    i = 1
    while i < 6:
        print(i)
        i += 1
def main():
    i = 1
    while i < 6:
        print(i)
        if i == 3:
            break
        i += 1
def main():
    i = 0
    while i < 6:
        i += 1
        if i == 3:
            continue
        print(i)
def main():
    i = 1
    while i < 6:
        print(i)
        i += 1
    else:
        print("i is no longer less than 6")

For loop

def main():
    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        print(x)
def main():
    for x in "banana":
        print(x)
def main():
    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        if x == "banana":
            break
        print(x)
def main():
    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        if x == "banana":
            continue
        print(x)
def main():
    for x in range(6):
        print(x)
def main():
    for x in range(2, 6):
        print(x)
def main():
    for x in range(2, 30, 3):
        print(x)
def main():
    for x in range(6):
        print(x)
    else:
        print("Finally finished!")
def main():
    for x in range(6):
        if x == 3:
            break
        print(x)
    else:
        print("Finally finished!")
def main():
    adj = ["red", "big", "tasty"]
    fruits = ["apple", "banana", "cherry"]

    for x in adj:
        for y in fruits:
            print(x, y)

User Input

  • Python 3.6 uses the input() method.
  • Python 2.7 uses the raw_input() method
def main():
    username = input("Enter username:")
    print("Username is: " + username)

Python stops executing when it comes to the input() function, and continues when the user has given some input.

Exception handling

Working with Files

Syntax

Attribuut Mode Description
“r” Read Default value. Opens a file for reading, error if the file does not exist
“a” Append Opens a file for appending, creates the file if it does not exist
“w” Write Opens a file for writing, creates the file if it does not exist
“x” Create Creates the specified file, returns an error if the file exists
“t” Text Default value. Text mode
“b” Binary Binary mode (e.g. images)
def main():
    f = open("demofile.txt")
def main():
    f = open("demofile.txt", "rt")

Reading files

def main():
    f = open("demofile.txt", "r")
    print(f.read())
def main():
    f = open("../demofile.txt", "r")
    print(f.read())

Read only part of the file

def main():
    f = open("demofile.txt", "r")
    print(f.read(5))

Read lines

def main():
    f = open("demofile.txt", "r")
    print(f.readline())
def main():
    f = open("demofile.txt", "r")
    print(f.readline())
    print(f.readline())
def main():
    f = open("demofile.txt", "r")
    for x in f:
        print(x)

Closing

def main():
    f = open("demofile.txt", "r")
    print(f.readline())
    f.close()

Writing files

open and read the file after the appending:

def main():
    f = open("demofile2.txt", "a")
    f.write("Now the file has more content!")
    f.close()

    #open and read the file after the appending:
    f = open("demofile2.txt", "r")
    print(f.read())

open and read the file after the appending

def main():
    f = open("demofile3.txt", "w")
    f.write("Woops! I have deleted the content!")
    f.close()

    f = open("demofile3.txt", "r")
    print(f.read())

Create a new file

“x”, “a”, “w”

def main():
    f = open("myfile.txt", "x")
def main():
    f = open("myfile.txt", "w")

Delete a file or folder

import os

def main():
    os.remove("demofile.txt")
import os

def main():
    if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
    else:
    print("The file does not exist")
import os

def main():
    os.rmdir("demodir")

Modules

Using a module

Create a file called mymodule.py with the following

def greeting(name):
    print("Hello, " + name)

In our main program we can import the module and can call the function defined in the module.

import mymodule

def main():
    mymodule.greeting("John")

Using variable in modules

If we extent mymodule.py with the following

person = {
  "name": "John",
  "age": 42,
  "country": "Ireland"
}

We can now access the variable person and use age defined within person

import mymodule

def main():
    age = mymodule.person["age"]
    print(age)

Output:

42

Import from a module

You can also import a certain section from a module

from mymodule import person

def main():
    print(person["age"])

Rename a module

We can rename a module during import

import mymodule as abc

def main():
    age = abc.person["age"]
    print(age)

Built-in modules

import platform

def main():
    x = platform.system()
    print(x)
import platform

def main():
    x = dir(platform)
    print(x)

Classes

Creating a class and object

class MyClass:
    a = 42

def main():
    myobject = MyClass()
    print(myboject.a)

The constructor method

During the instantiation of a class the constructor method is called to initialize the object. In Python the method name __init__ is reserved for this purpose.

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

person1 = Person("John", 42)

print(person1.name)
print(person1.age)

Define an object method

Object methods are functions that belong to the object and operation withing the context of the current object.

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

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

person1 = Person("John", 42)
person1.myfunc()

The self parameter

The self parameter is a reference to the current instance of the class and has been specified in PEP-8, but isn’t a reserved keyword. The name of first argument can be anything you want.

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

    def myfunc(xyz):
        print("My name is " + xyz.name)

person1 = Person("John", 42)
person1.myfunc()

Object actions

Modify an object property

person1.age = 40

Delete an object property

del person1.age

Delete an object

del person1

Inheritance

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

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

class Engineer(Person):
    pass

engineer1 = Engineer("John", 42)
engineer1.myfunc()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

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

engineer1 = Engineer("John", 42, "Electronics")
engineer1.myfunc()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

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

engineer1 = Engineer("John", 42, "Electronics")
engineer1.myfunc()

PIP: Using packages and virtual environments

PIP is a package manager for Python for packages or modules

Create and start the virtual environment

First we create virtual environment

$ python3 -m venv .venv
$

To activate the

$ source .venv/bin/activate
(.venv) $ python
Python 3.9.2 (default, Feb 20 2021, 00:00:00) 
[GCC 10.2.1 20201125 (Red Hat 10.2.1-9)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib64/python39.zip', '/usr/lib64/python3.9', '/usr/lib64/python3.9/lib-dynload', '/workspaces/python-examples/.venv/lib64/python3.9/site-packages', '/workspaces/python-examples/.venv/lib/python3.9/site-packages']
>>>

Managing packages with pip

Since Python 3.4, Pip is installed by default en

$ source .venv/bin/activate
(.venv) $ python -m pip search camelcase
$ source .venv/bin/activate
(.venv) $ pip search camelcase
(.venv) $ pip install camelcase
Collecting camelcase
  Using cached camelcase-0.2.tar.gz (1.3 kB)
Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
Installing collected packages: camelcase
    Running setup.py install for camelcase ... done
Successfully installed camelcase-0.2
(.venv) $ pip install camelcase==0.1
Collecting camelcase==0.1
  Downloading camelcase-0.1.tar.gz (1.2 kB)
Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
Installing collected packages: camelcase
  Attempting uninstall: camelcase
    Found existing installation: camelcase 0.2
    Uninstalling camelcase-0.2:
      Successfully uninstalled camelcase-0.2
    Running setup.py install for camelcase ... done
Successfully installed camelcase-0.1
(.venv) $ pip install --upgrade camelcase
Collecting camelcase
  Using cached camelcase-0.2.tar.gz (1.3 kB)
Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
Installing collected packages: camelcase
  Attempting uninstall: camelcase
    Found existing installation: camelcase 0.1
    Uninstalling camelcase-0.1:
      Successfully uninstalled camelcase-0.1
    Running setup.py install for camelcase ... done
Successfully installed camelcase-0.2
(.venv) $ pip show camelcase
Name: camelcase
Version: 0.2
Summary: Converts a string to Camel Case
Home-page: http://www.craigaddyman.com
Author: Craig Addyman
Author-email: craig.addyman@googlemail.com
License: MIT
Location: /workspaces/python-examples/.venv/lib/python3.9/site-packages
Requires: 
Required-by:
(.venv) $ pip list
Package    Version
---------- -------
camelcase  0.2
pip        20.2.2
setuptools 49.1.3

Install all dependencies

(.venv) pip freeze>requirements.txt
(.venv) cat requirements.txt
camelcase==0.2
(.venv) $ pip uninstall camelcase
Found existing installation: camelcase 0.2
Uninstalling camelcase-0.2:
  Would remove:
    /workspaces/python-examples/.venv/lib/python3.9/site-packages/camelcase-0.2-py3.9.egg-info
    /workspaces/python-examples/.venv/lib/python3.9/site-packages/camelcase/*
Proceed (y/n)? y
  Successfully uninstalled camelcase-0.2
(.venv) $ pip install -r requirements.txt
Collecting camelcase==0.2
  Using cached camelcase-0.2.tar.gz (1.3 kB)
Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
Installing collected packages: camelcase
    Running setup.py install for camelcase ... done
Successfully installed camelcase-0.2