Categories
Python

Python Crash Course for Programmers

This is the fastest intro course on Python I have ever delivered. It was meant for a group of PHP developers that wanted to use/modify a Django application as part of a larger project. Therefore this is NOT an introductory course. This is probably useful only for people with a bit of knowledge of another programming language that wants to get up to speed quickly. Besides previous familiarity with programming, I suggest you to:

to get as much as possible from this mini-course (some exercises also below).

What is Python?

Python is an interpreted, dynamically typed language. It is often used as a “glue” language that allows combining different systems, as well as a standalone language. Some areas on which Python is popular include:

  • Data analysis / machine learning / scientific computing.
  • Web development (Django, Flask, FastAPI).
  • System Administration.

It is relatively easy to learn, with concise syntax.

One can run Python code in different ways:

  • Write a file with extension .py and then execute python myfile.py.
  • Use the interactive interpreter in the command line.
  • Use Jupyter Notebook, which is a web-based IDE.

hello.py

print("Ahoj!")
  • print is a function.
  • "Ahoj" is an argument.

name.py

name = input()
print(f"Hi {name}!")
  • Python does not require you to specify it from the beginning (unlike for instance C++ or Java).
    • Supported types: Integer, Float, Boolean, None.
  • You can check the type with type() function.

Conditional Statements

x = input()

if x>0:
    print("x is positive")   
elif x<0:
    print("x is negative")
else:
    print("x is zero")

Sequences

name = "Pablo"
records = (123, "Some User", 721324890, 123.45)
names = ["Pablo", "Marek", "Petra", "Jana"]
letters = 'abcdefg'

Indexing

  • First element in a sequence is 0.
  • Last element is -1.
  • letters[1:7:2] returns 'bdf'.

Strings

  • There is no “character” type in Python.
  • 'Pablo'.upper()
  • 'Pablo'.lower()
  • nosferatu.title()
  • 'P' in 'Pablo'
  • 'Pablo;Maldonado;Prague'.split(';')
  • '_'.join(['Pablo', 'Maldonado'])

Lists

  • names = ["Pablo", "Marek", "Petra", "Jana"]
  • names.append("Olga")
  • names.append("Elmo")
  • names.pop()
  • names.remove("Marek")
  • sorted(names) # returns sorted list
  • names.sort() # in-place sorting
  • names[1] = 'Pavel'

Tuples

  • Tuples are similar to lists, except that they are immutable.
records = (123, "Some User", 721324890, 123.45)
records[1] = "Another User" # will fail

Dictionaries

  • Collections of key-value pairs.
ages = {"Pablo":25, "Olga":30}
ages["Pablo"] = 30
ages["Olga"] += 1
  • Dictionaries can nest other values
user1 = {'name':'Pablo', 'hobbies':['box','movies','beer']}
user2 = {'name':'Petra', 'hobbies':['climbing','beer']}
users = {'u-001':user1, 'u-002':user2}

Loops

  • Simple loops.
for i in range(5):
    print(i)
  • Loops over sequences.
names = ["Pablo", "Marek", "Petra", "Jana"]
for name in names:
    print(name)

More Loops

  • Loops over dictionaries
ages = {"Pablo":25, "Olga":30}
ages["Pablo"] = 30
ages["Olga"] += 1

for key, value in ages.items():
    print(f'The age of {key} is {value}')
  • Conditions on loops.
i = 0
while i &lt; 10:
    print(i)
        i += 1 # i = i+1

Functions

def square(x):
   return x*x

for i in range(10):
   print("{} squared is {}".format(i, square(i))

Exercises

  • Calculate the number of vowels in a string.
  • Calculate the number of capital letters in a string.
  • Consider a beers dictionary defined as follows:
beers = {
    'Kozel':30, 
    'Pilsner':40, 
    'Matuska':60, 
    'Antos':55
    }

Write a program that takes a user input of the form: beer1;beer2;beer3 and calculates their bill. You can use the sum(<list>) function, where <list> represents a list of values.

List comprehensions

  • Short notation to apply operations on lists.
numbers = (1, 2, 3, 4, 5)
squares = [num**2 for num in numbers]
vals = ["1.5", "3.14", "9.87"]
float_vals = [float(val) for val in vals]

List comprehensions (cont.)

vals = ["1.5", "3.14", "9.87"]
vals = [float(val) for val in vals if float(val) &lt; 5]
vals_mask = [1 if float(val) &lt; 5 else 0 for val in vals]

List comprehensions and lambda functions.

parse = lambda val: float(val)
vals = [parse(val) for val in vals]

Exercise

  • Given a string of values separated by a whitespace, that is, something like this:
    10 abc 20 de44 30 55fg 40
    write a function that identifies the numbers and sums them. In this case, the output should be 100.

Modules and packages

  • You can invoke pieces of code from one file into another.

functions.py

def square(x):
    return x*x

for i in range(10):
    print("{} squared is {}".format(i, square(i))

modules.py

from functions import square
print(square(10))
  • Trivia: What would happen when you run modules.py?

Modules and packages (cont.)

  • When you import a file, Python runs everything inside by default. We need to modify functions.py to prevent this.
def square(x):
    return x*x

def main():
  for i in range(10):
      print("{} squared is {}".format(i, square(i))

if __name__ == "__main__":
    main()

Modules and packages (cont.)

  • if __name__ == "__main__" simply means: execute the code below only if this is the main program being run.
  • To import a file from a subfolder, you need to create an empty __init__.py file in the folder first.

Classes

import math
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def magnitude(self):
        return math.sqrt(x*x+y*y)

p = Point(3,5)
print(p.x)
print(p.magnitude())

Classes and Inheritance

class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def __str__(self):
        txt = f"A {self.year} {self.brand} {self.model}"
        return txt
class ElectricCar(Car):
    def __init__(self, brand, model, year, battery_life):
        super().__init__(brand, model, year)
        self.battery_life = battery_life

    def __str__(self):
        base = "A {0} that goes for {1} km"
        txt = base.format(self.brand,self.battery_life)
        return txt

Decorators

def argument_test_natural_number(f):
    def helper(x):
        if type(x) == int and x &gt; 0:
            return f(x)
        else:
            raise Exception("Argument is not an integer")
    return helper

@argument_test_natural_number
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
for i in range(1,10):
    print(i, factorial(i))
print(factorial(-1))

Useful References