Table of Contents

Quick start with Python: There is one big problem with programming courses for beginners.  They guide you trough the long introductions, history facts, lots of theory.

Usually, most people simply quit before getting to the “good stuff”.

Let us try a bit different approach.

Lets make our quick start with Python

Here is a list of things that you need to know for now:

  • Firstly, there is a lot of programming theory around Python and you will learn it in time.
  • Secondly, Python has 2 major versions (Python 2x and Python 3x) and you will learn the differences in time.
  • Thirdly, you will have to setup development environment for Python.
  • Finally, you have fantastic Python documentation at https://docs.python.org/3/tutorial if you prefer book like learning.

For now, let us postpone most of the standard steps and simply write and run our first Python program.

Task: Write a program which reads input number and tells us if that number is positive (bigger than 0) or negative (less than 0).

Hints:

  • There are online Python compilers, which allows you to write Python code in your browser and execute it. Yes, you don’t have to setup anything at this moment. We can simply get started.
  • Try not to do copy paste, because you want to get used to typing, also known as coding… 😉
  • Python cares about indents (tabs). When typing examples, pay attention to this.

For quick start with Python open compiler at this link: https://www.onlinegdb.com/
online_python_compiler

Once you open this link, type in the solution as provided here.

x = int(input("Please enter an integer: "))

if x < 0:
    print('The number you have entered is negative')
elif x == 0:
    print('The number you have entered equals zero')
else:
    print('The number you have entered is positive')

Final solution should look like this:

python compiler example
python compiler example

Once you successfully typed the solution in Python compiler, click Run.

python compiler example response
python compiler example response

Program will ask you to enter some number (for example 20). After doing this and clicking enter, program will let you know if the number is positive or negative.

Yay! You just made your first Python program!

Congratulations!

(rainbow unicorns all around, feel that heat of instant gratification, etc, etc.)

Now, what does this program actually do?

For now, just notify couple of things:

  • input() – this is a Python function that is used to get the input from the console. Meaning, it allows someone to type in something and send it to your program. Later, program decides what to do with this.
  • int() – function which tells program to treat some information as integer (otherwise program wouldn’t know how to treat something)
  • int(input(“Please enter an integer: “)) – get something from console and treat it as an integer
  • x = – here ‘x’ represents a ‘variable’. Variables are used to store some information in memory and store it under some name (variable name)
  • x = int(input(“Please enter an integer: “)) – get something from console, treat it as an integer and store it under a name ‘x’
  • if x < 0: – In most of the programming languages IF is a standard way to make a condition. If some condition is good, do some logic..
  • elif – If the first condition is not good, check some other condition.
  • else – If none of the previous conditions were good, do this anyway.
if x < 0:
    print('The number you have entered is negative')

This part of the code says: If the value stored in ‘x’ is smaller then 0, then print out “The number you have entered is negative” message in the console.

elif x == 0:
    print('The number you have entered equals zero')

This part of the code says: If the first condition is not good, and the X is equal to 0, then print out the message in the console.

else:
    print('The number you have entered is positive')

The last part of the code says: If any of the previous conditions were not good (so, X is not smaller than 0 and it is not 0), then print out “The number you have entered is bigger then zero”, which is the only possible option.

That is it. You coded your first Python program.

Breaking and bug-fixing in Python

In this lesson we will learn how to break our program.

More importantly, we will learn how to recognize what is broken and how to fix it.

This is a serious matter.

If you continue your goal of becoming a developer you will break programs a lot. You will break them while you learn, while you work as a junior developer, while you work as a senior developer. You will break them in testing environment, in production and in your dreams as well.

Yup, simply put, but let us use a proper terminology here:

  • Bug – an error in code
  • Debugging – process of finding a bug (there are different approaches here, more on that later)
  • Error log – list of the error messages
  • Stack trace – Message which is returned by compiler when program is stopped because of error
  • Syntax bug – an error which was introduced because you coded something wrong (i.e. you entered IFF instead of IF)
  • Semantic bug – and error in logic. Meaning, program is coded correctly, but logic is not good, so the end result is not good as well.

Hints:

  1. Syntax bugs are easier to find and fix, because they will stop your program from execution.
  2. Semantic bugs are harder to find, because everything works but the logic is wrong.
  3. At the beginning of your journey, you will make lots of syntax bugs (which is ok).
  4. In time, syntax bugs will go away, and they will be replaced with semantic bugs.

But let’s back to what we were doing, breaking our first program.

Just as a reminder, at the previous lesson, we made a program which is determining if number is bigger or smaller than zero.

x = int(input("Please enter an integer: "))

if x < 0:
    print('The number you have entered is negative')
elif x == 0:
    print('The number you have entered equals zero')
else:
    print('The number you have entered is positive')

Then, we executed this program in https://www.onlinegdb.com/
online_python_compiler  and everything worked properly.

Now, let’s introduce some syntax bugs and see what will happen.

First bug: At the line 5, we want to change == with = to make it look like ‘elif x = 0:’

  • In programming there is a difference between == and =.
  • Two equal signs check if the items are the same, example x == 5 (this checks IF x is equal 5)
  • One equal sign assigns value to a variable, example x = 5 (this means that 5 is assigned to x)
  • Essentially, this will be a bug, because in IF-ELIF-ELSE structure we need checks ‘==’ and not assignment ‘=’
bug1 error log
bug1 error log

This is a message we will get after executing ‘buggy example’. Python compiler will tell us that there is a “SyntaxError” and point out to the problematic line. However, compiler will not tell us how to resolve it. In our case, it is simple. Since we introduced a bug intentionally, we can simply solve it by using ‘==’ instead of ‘=’.

Whole point of this example is to intentionally break something, so we can see what will the compiler complain about. Later, when we make a real mistake (this one or similar) error messages will not be so strange for us.

Second bug: At the line 3, we will change ‘if x < 0:’ with ‘if x < 10:’

  • This is not a syntax bug, because syntax will still be correct, program will work.
  • This is a semantic bug, because first IF will not calculate things correctly.
  • Result will be that numbers smaller than 10 will be recognized as negative (i.e. 5 will be reported as negative).
  • As you can see, this is a logical bug, which is easy to detect here, but somewhere else (in bigger code) it would cause issues.

If you run this example, result will be like this

semantic bug 7 reported as negative
semantic bug 7 reported as negative

That is it for this lesson. We broke our program two times and fixed it.

First time it was a syntax bug and second time it was a semantic bug.

There will be a dedicated lessons on debugging, but for now this will be sufficient.

Homework:

  • Play with this code, break it intentionally.
  • Change some lines and observe what will be reported as error in console.
  • Try to make semantic bug as well, not only the syntax ones.

Commenting and documentation in Python

Long story short: In the first lesson we coded our first Python program. Then in the second lesson we broke it intentionally and fixed it again. Finally, we want to document it.

Some vocabulary:

  • comment – code which will not be executed (it is still in our program, but compiler will ignore it)
  • inline comment – comment which is commenting only one line
  • comment block – comment which is commenting multiple lines of code
  • doc-block – comment which is actually a documentation (usually contains description of function, methods, authors, etc.)
  • Code smell – This is a programming jargon, which usually means that there are too much comments. In this case, it is suspected that code is not good, so the comments are there to (like a deodorant) to improve a bad smell of rotten code.

Disclaimer: Throughout this course, examples will have lots of comments (even where something is obvious). Reason for this is to make them understandable for learning purposes. In a production, lots of these comments would be excluded. Furthermore, lots of approaches and oversimplified examples would never be used in a production code (… or would they…).

Ok, lets put some comments (documentation) in our code.

We will take the example from the previous lesson and make it look like this.

Quick reminder, we are using Online Python compiler – https://www.onlinegdb.com/
online_python_compiler

Note: As you can see, this time you have only screenshot (no code example), which means you will have to type it (no copy paste this time).

Python comments example
Python comments example

Single line comment

  • To make a single line comment, we write # at the beginning of a code line. Example on line 6.
  • If we put a # somewhere in the middle of the line, then only part of that line will be commented (right part of the line). Examples on lines 10, 12 and 13.

Comment block

  • Triple quotes ”’ are used to make a comment block (multiple lines of code which are commented).
  • Comment block is usually used to give us some information about code (task, author, date, etc.). Example lines 1-4.
  • Comment block can also be used to make part of the code ‘inactive’. Meaning, code will still remain, but it won’t be executed. Example lines 17-20.

What is Python?

For some reason programming courses give you long and tiresome explanations on what Python is.

At this point, this one should be simple.

Here is a fancy definition for you.

Python is a programming language. With it, you can do stuff.

Here is a short list of things you should keep in mind

  • Python is Object Oriented programming language (like Java, C#, PHP, etc.).
  • Python has two tracks 2.x and 3.x (where 2.x track will be supported up to 2020).
  • Python has implementations for Windows, Linux and Mac OS operating systems.
  • Python has lots of external libraries (already programmed functionalities) which are available for use.
  • Python has a strong community (but other programming languages have strong communities as well).
  • Python has very simple syntax and that makes is a good language for beginner developers.
  • Python has a very wide scope of usage (web development, automation, AI, architecture, etc.) which makes it a good choice for a senior developers as well.

One size does not fit everything

  • Python is just another tool.
  • Knowing Python is as good and useful as knowing any other programming language.
  • Some companies will give you great salary as a Python developer, other companies won’t need this and won’t care.
  • Knowing Python alone won’t get you far. You will have to know libraries and have practical experience.

Most importantly

  • Learning Python is essentially learning general programming concepts executed with Python syntax.
  • Keep in mind, that lots of things that you learn here is reusable.
  • Knowing Python will help you in learning any other programming language really fast.

Setting up Python environment

What is the development environment?

For me, setting up a development environment is a list of these important things:

  • Choosing my development platform (Windows, Linux or Mac OS).
  • Installing and configuring programming language that I want to use (in this case Python).
  • Finding a proper code editor or IDE for what I want to do.
  • Find a good syntax checker tool (something to tell me if my code is correct).
  • Find a good code completion tool.
  • Connect my project to some code repository (GIT code repository)

Choosing development platform

For this course you should probably stick with your current platform, being that Windows, Linux or Mac OS. Initial installation of Python will be different, but programming it self will be the same.

Installing and configuring programming language on your platform

We want to install Python 3.7.x to our computer.

Note: If you find official Python installation tutorial too complicated for you, please comment below and I will make an additional lesson (or video tutorial) for this step.

There are multiple ways to install Python to your development. Most common one is to go to https://www.python.org/downloads/ , choose your platform and download installation.

Quick start with Python - python installation
python installation

After downloading and installing of the Python, you will get a Python Command Line Tools, where you can run Python commands directly.

Finding a proper code editor or IDE

An IDE (or Integrated Development Environment) is a program used for software development. This means that IDE has integration of multiple tools specifically designed for software development. These tools might include: code syntax checker, code control tools, validators, file system organizers, version control, etc.

On the other hand code editors are more simple, it is used plainly for editing code.

For our course both IDE or code editors would work. While preparing this course I am using Sublime editor, but you should install and try several different ones and see which one works for you the best.

At this point, we will not need anything else.

Homework for you:

  • Install Python on your machine.
  • Install two code editors or IDEs on your machine (Sublime and one more from the list).
  • Choose code editor or IDE which you find “prettier” or more suitable for you.

Note: If you have troubles with installing Python or setting up code editor or IDE, please comment below.

This course is still in a development and new lessons are being created daily. During this period course will be Free to enroll.

Python is one of the most powerful and versatile programming languages in the world.

  • Imagine yourself programming your own applications, create games, design algorithms or even program an artificial intelligence or robot friend.
  • Furthermore, learning Python can be a first step in your career as a software engineer, web developer, data scientist or mobile developer.
  • Finally, imagine building a portfolio which would enable you application for Google, Amazon or one of the big tech companies.

Yes, all of this sounds very interesting and if you can picture yourself doing one of these things then you are on the right path.

How do you start with programming and Python?

It is actually quite simple.

  • You need a good project driven tutorials/courses or someone to work with you 1 on 1.
  • You need lots of good examples and you need to write lots of code.
  • Along the way, while you code, you need to learn additional concepts, vocabulary, some theory and learn how to combine it all together.

Step 1 – Define your goals, right here, right now

  • Why do you want to learn Python?
  • What’s your learning style?
  • What’s your coding level and where do you want to get?

Step 2 – Check out preview lessons of this course

Preview of this course is not small. You actually have a whole chapter (5 lessons) available for a preview.

You don’t have to register or do anything to start.

Step 3 – Enroll this course

If you find these lessons and my teaching style interesting and suiting for you, then you can enroll the course.

Difference between 2x and 3x

Difference between 2x and 3x

Python has two major versions, 2x and 3x, and these versions have some differences.

Ok, that’s all that I have for you.. ?

But for real now, this lesson is actually an research assignment.

Here is a situation for you

Imagine that you are experienced developer who has a new project in Python. Your task is to do a quick research about this programming language and decide which version to use. Someone told you that Python has 2x version and 3x version and that they are not backward compatible.

You need to do the research, figure out why this is so and determine which version you want to use and why.

Research materials for you

Note: You can use any other source in your research.

What did you come up with? Which version of Python would you use and why?

Quick start with Python – libraries and modules

Let me tell you a story about three little piggies and a bad wolf.

Three little piggies had a deadline to build their strong house to hide from big bad wolf. They did not use completed parts (windows, doors, bricks). Instead of this, three little piggies wanted to do everything on their own, from zero. Three little piggies didn’t make it till deadline and the big bad wolf ate them.

The end.

What is the moral of the story?

  • In real life you can not program everything by your self.
  • Software development is very fast and aggressive field, and you have to use all the tools at your disposal.
  • Also, you have to reuse what other people already made, instead of “reinventing the wheel”.
  • Otherwise, you will be eaten by deadlines and big bad wolves (you get the point).

Python library is a collection of functions and methods that allows you implement many functionalities without writing them yourself.

Having that in mind, Python libraries are very important.

At this stage, I just want you to be aware that Python libraries exist.

  • Library is a collection of modules.

Ok, so what is the module then?

Module is a smaller independent part of the code that can be reused multiple times to create some more complex logic. Essentially, module is something that someone coded while ago, and now you can simply use it.

  • Modules must be imported to a main project, in order to use them.
  • We can import whole module or only a specific functions from within them.
  1. import example_module
  • In this example, we are importing example_module
  1. import example_module import *
  • In this example we are importing everything from a single module
  1. import example_module as some_other_name
  • In this example, we are importing module under some other name

We will use modules in the examples that follow.

For now, just keep in mind that you don’t have to code everything from zero.

There are a ways to reuse what someone else coded, and you do that by using modules and libraries.

Quick start with Python – Code indentation

Every programming language needs some way to recognize code blocks.

Code blocks are separated units of code which are executed in some order.

In general, there are two ways of recognizing code blocks:

  • With brackets {}
  • With indentation (tabs or spaces)

One of the most distinctive features of Python is its use of indentation to mark blocks of code.

Examples of programming languages that use brackets for code blocks: Java, PHP, C#, etc.

Let’s revisit one of the examples from the beginning of this course.

def is_integer_negative(x):
    """
    Check if the integer is negative

    Keyword arguments:
    x - integer which needs to be checked
    """

    if x < 0:
        print('The number you have entered is negative')
    elif x == 0:
        print('The number you have entered equals zero')
    else:
        print('The number you have entered is positive')
    return;

As you can see, in this example we have defined a function called is_integer_negative(x).

All of the code lines inside this function have indent of one tab. Meaning, these lines form a code block executed under this function name.

Now, further down, after IF line, there is a print with two tab indent. This means that print() forms a code block, which is executed under IF.

Important: Code indention is something that comes naturally, with exercise. For now, just keep in mind that Python is sensitive on indent, so if you make different indent your program will behave differently.

Quick start with Python – variables and constants

Python variables

  • A variable is a named location in memory which is used to store data.
  • Variables are a container that holds data which can be changed later throughout execution of our program.
age = 18

This is an example where we define variable age, with a value 18.

age = 18
age = 19

We said that variables can change in time. First, age was 18, and later in program something changed it to 19.

a, b, c = 18, 2.1, "Hallo"

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

Here is an example where we assign multiple values to multiple variables. In this example we have three variables a,b,c and we are assigning the values 18, 2.1. and “Hallo” respectively. Notice that we can assign different types of values, integer (whole number), floating point number or string (text).

a = b = c = "same value for all three variables"

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

Python Constants

  • A constant is a type of variable whose value cannot be changed.
  • Constants are a container that holds data which can not be changed later in our program.
import constant

print(constant.PI)
print(constant.EARTH_GRAVITY)

constants.py

PI = 3.14
EARTH_GRAVITY = 9.8

Imagine that we have a program which calls math PI and EARTH_GRAVITY variables. In this example we called package constant, where PI and EARTH_GRAVITY are defined. If file constant.py has PI = 3.14 and EARTH_GRAVITY = 9.8 then these values will be printed.

Quick start with Python – Comments

We use comments in the code to notate our work, to explain parts of the code. Sometimes, we use comments to exclude parts of the code from execution (to test it during development). Essentially, comments are parts of the code that will be ignored during the execution.

All programming languages have comments. Usually, there are several types of comments:

  • Single-line comments (sometimes called in-line comments)
  • Multi-line comments (sometimes called comment blocks)
  • Documentation comments (sometimes called docblocks)

Single-line comments

# This is an example of single-line comment in Python

Single-line comments are created simply by beginning a line with the hash (#) character, and they are automatically terminated by the end of line.

Multi-line comments

'''
This is an example of multi-line comment.
Multi-line comments span accross the several lines.
They are also called a code blocks.
'''

Multi-line comments are created by adding ”’ at the beginning and ”’ at the end of the comment block.

Everything between these delimiters is considered as a comment.

Documentation comments

Documentation comments are nothing more than a convention on how to write comments to document your functions or classes.

Here I have an assignment for you again.

Go to the https://www.python.org/
dev/peps/pep-0257/ and learn about proper documenting of Python functions and classes.

What do you make of this? Comment below and earn some Codies.

Commenting vs. Documenting Code

There is one important thing. Code should tell you how something works, and comments should explain you why.

You should never write comments to explain bad code, this is considered as a bad practice (aka. “code smell”).

You should use comments to explain the logic (big picture wrapped around that code).

Essentially, your comments should provide big picture, some insights that good programmer can not figure out just by reading your code.

Quick start with Python – Math Operators is Python

Operation is programming languages (including Python) can be divided into:

  1. Arithmetic operations
  2. Relational operations
  3. Logical operations
  4. Bit operations
  5. Assignment operations
  6. Special operations

In this lesson, we will quickly review these operations and several simple examples to demonstrate them.

Quick start with Python – Arithmetic operations

# Examples of an arithmetic operators 
a = 20
b = 10

# Addition of numbers 
add = a + b 

# Subtraction of numbers  
sub = a - b 

# Multiplication of number  
mul = a * b 

# Division(float) of number  
div_float = a / b 

# Division(floor) of number  
div_floor = a // b 

# Modulo of both number 
mod = a % b 

# print results 
print(add) 
print(sub) 
print(mul) 
print(div_float) 
print(div_floor) 
print(mod) 

Quick start with Python – Relational operations

# Examples of Relational Operators 

a = 50
b = 10
c = 10

# a > b is True
print(a > b) 

# a < b is False
print(a < b) 

# a == b is False 
print(a == b) 

# a == c is True
print(a == c) 

# a == b is False 
print(a == b)

# a != b is True 
print(a != b)

# a >= b is False 
print(a >= b)

# a <= b is True 
print(a <= b)

Quick start with Python – Logical operations

# Examples of Logical Operator 

a = True
b = False
c = False

# a and b is False 
print(a and b) 

# a or b is True 
print(a or b) 

# a or b or c is True 
print(a or b or c) 

# b or c is False
print(b or c) 

# not a is False 
print(not a) 

Bit operations

  • We won’t deal with bit operation at this point.

Assignment operations

=Assign value of right side of expression to left side operandx = y + z
+=Add AND: Add right side operand with left side operand and then assign to left operanda+=b     a=a+b
-=Subtract AND: Subtract right operand from left operand and then assign to left operanda-=b       a=a-b
*=Multiply AND: Multiply right operand with left operand and then assign to left operanda*=b       a=a*b
/=Divide AND: Divide left operand with right operand and then assign to left operanda/=b         a=a/b
%=Modulus AND: Takes modulus using left and right operands and assign result to left operanda%=b   a=a%b
//=Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operanda//=b       a=a//b
**=Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operanda**=b     a=a**b

Special operations

  • We won’t deal with special operations at this point.

Strings and Escape Sequences

String is a combination of characters stored within a single variable. To write the content of the string, we use print() function.

String examples

wellcome_message = "Hello client, welcome to our banking software!"

# We can use print to get the complete string
print(wellcome_message)

# We can use print to get the first character or string 
print(wellcome_message[0])

# We can use print to get the last character or string 
print(wellcome_message[-1])

# We can use print to get part of the characters, i.e. first 4 (between 0 and 4)
print(wellcome_message[0:4])


'''
For example, if we had two variables firstname and lastname
and we wanted to get initials
'''

firstname = 'Milan'
lastname = 'Latinovic'

# Get firts characters of the firstname and lastname and combine them with +
print(firstname[0] + lastname[0])

# Or maybe put a dots between, to make it look prettier
print(firstname[0] + "." + lastname[0] + ".")

There are lots of functions used to manipulate with strings, we will cover them in next lessons.

Escape Sequences

In Python strings, the backslash “\” is a special character, also called the “escape” character.

It is used when we need some special characters, i.e.:

  • “\t” is a tab,
  • “\n” is a newline
''' 
Let us look at the example where we want to have "April's account balance is:"

Problem with upper sentence is that it includes '
If we try to write print('April's account balance is:') this will not work
because 's will stop print function.

We need to escape ' character by writing it as \'
'''

print('April\'s account balance is:')


'''
Let us look at the example where we need message in two rows.

Welcome client!
Your balace is 2000.

In order to write this we need to use \n for a new row
'''

print('Welcome client!\nYour balance is 2000.')

Quick start with Python: Here is a list of all Python escape characters, source: LinuxConfig.org

Escape SequenceDescriptionExampleOutput
\\Prints Backslashprint(“\\”)\
\`Prints single-quoteprint(“\'”)
\”Pirnts double quoteprint(“\””)
\aASCII bell makes ringing the bell alert sounds ( eg. xterm )print(“\a”)N/A
\bASCII backspace ( BS ) removes previous characterprint(“ab” + “\b” + “c”)ac
\fASCII formfeed ( FF )print(“hello\fworld”)hello world
\nASCII linefeed ( LF )print(“hello\nworld”)hello world
\N{name}Prints a character from the Unicode databaseprint(“\N{DAGGER}”)
\rASCII carriage return (CR). Moves all characters after ( CR ) the the beginning of the line while overriding same number of characters moved.print(“123456\rXX_XX”)XX_XX6
\tASCII horizontal tab (TAB). Prints TABprint(“\t* hello”)    * hello
\tASCII vertical tab (VT).N/AN/A
\uxxxxPrints 16-bit hex value Unicode characterprint(“\u041b”)Л
\UxxxxxxxxPrints 32-bit hex value Unicode characterprint(“\U000001a9”)Ʃ
\oooPrints character based on its octal valueprint(“\043”)#
\xhhPrints character based on its hex valueprint(“\x23”)#
Source: LinuxConfig.org

String Methods

Here is an quick start with Python example of several variables that might appear in banking software.

We can use string methods against these variable is lots of ways.

Here are couple of quick and simple examples.

wellcome_message = "Welcome to our Banking system"
client_firstname = "John"
client_lastname = "Johnson"
balance_message = "Your account balance is: "
client_password = "324!@#df!df"
balance = 2000

print("Welcome to our Banking system John. Your account balance is 2000.")

# Function len() returns the length of a string
print(len(client_password))

# We can use len() it to check the length of the password
if(len(client_password) > 9):
    print("Your password strength is good.")
else:
    print("Your password strength is weak. Password is under 9 characters of length.")

# Function lower() returns whole string in lower case 
print(wellcome_message.lower())


# Function upper() returns whole string in lower case 
print(wellcome_message.upper())

Hint: Notice that some methods are used by giving them variable as input parameter, i.e. function(variable) Other functions are used by assigning them to variable with . i.e. variable.function()

Furthermore, there are lots of string methods that will return a logical value, true or false. We can use these functions to check various things.

MethodMetrod returns True if
our_string.isalnum()String consists of only alphanumeric characters (no symbols)
our_string.isalpha()String consists of only alphabetic characters (no symbols)
our_string.islower()String’s alphabetic characters are all lower case
our_string.isnumeric()String consists of only numeric characters
our_string.isspace()String consists of only whitespace characters
our_string.istitle()String is in title case
our_string.isupper()String’s alphabetic characters are all upper case

Homework:

  • Research join() method.
  • Research split() method.
  • Research replace() method.

These methods will be used later, when we deal with data structures.

  • For now, just “Google them” and try to understand what are they used for.
  • It is extremely important that you are capable of researching or finding some method that you need in development. It is not possible to know all the methods “by heart” and it is not needed.
  • Reading of the documentation is always better than trying to remember all the small details.

Introduction to functions in Python

Quick start with Python includes a knowledge of functions.

Functions are named blocks of code designed to do one specific job. With functions, we write code once, and run it whenever we need to accomplish that specific task.

For example, if we create a function called open_bank_account() then:

  1. Whole logic for opening a bank account would be implemented inside this function.
  2. We would call this function whenever we need it (any time when we want to open a bank account for some customer).

Functions can take in the information they need, and return the information they generate.  Using functions effectively makes your programs easier to write, read, test, and fix.

Definition/identity of a function

The first line of a function is its definition, marked by the keyword def. The name of the function is followed by a set of parentheses and a colon. The content within a function, a logic itself, is indented one level.

In this example we coded a say_hallo() function which prints “Hallo!” in console. As simple as that.

def say_hallo():
    print("Hallo!") 

say_hallo()

There are much more use cases for functions

  • Function which accepts list as an argument
  • Function which modifies a list
  • Function which collects an arbitrary number of arguments
  • Function which collects an arbitrary number of keyword arguments
  • Functions which is stored in a module
  • Function imported from a module
  • Function with an alias
  • Selective importing of functions from a module

These topics are not covered in this lesson.

Important reminder

As any other programming language, Python too has a naming conventions, provided at the official Python site.

These naming conventions are not the same as in the other programming languages.

  • For example, in Java or PHP, we would name functions with camel-case, where in Python we do it in small-caps separated by underscore.
  • As a result, function in Java or PHP would be called openBankBalance(), but in Python will be open_bank_balance().

Let’s make one thing clear, both function names would work in all programming languages. The only difference is that Java or PHP sees openBankBalance() as pretty and clean, while Python sees open_bank_balance() as pretty and clean.

If you wonder which approach is correct? Well, both and none of them. 🙂

Simply use the convention of the programming language that you are working with.

Quick start with Python – Passing arguments to functions

Passing argument to a function

In this example we coded a say_hallo function which accepts an argument. This argument is name which is then included in a Hallo message.

def say_hallo(user):
    print("Hallo " + user + "! Welcome to our system!") 

say_hallo("Maria")

Passing arguments as positional arguments

In this example we created the open_bank_account function. This function takes two arguments, user for which we are opening the account and the account type that we want to open. We are calling this function once. In this call, we are opening an “savings” account for person called “Maria”.

def open_bank_account(user, account_type):
    print("Hallo " + user + "!")
    print("Your " + account_type + " account is opened!")

open_bank_account("Maria", "savings")

Passing arguments as keywords

In this example we have the same function as above. But this time, notice that the call of the function is different. We are calling function two times. First time, we are calling it for “Maria” and for “savings” account. Second time, we are calling it for “savings” account and for “John”.

Therefore, mportant thing to notice here is that we called function with two arguments, but the arguments don’t have the same order. Still, in both cases function works properly, because we assigned arguments to a proper keywords (i.e. user = “Maria”, or account_type = “savings”).

def open_bank_account(user, account_type):
    print("Hallo " + user + "!")
    print("Your " + account_type + " account is opened!")

open_bank_account(user = "Maria", account_type = "savings")
open_bank_account(account_type = "savings", user = "John")

Default values and optional arguments

Functions with default values

In this example we assigned a default value to account_type argument. This default value is “checking”. So, if we call function without account_type, then default account type will be “checking”. In our example, Maria will get an “savings” account, but John is called in a function without account_type argument, so he will get the “checking” account.

def open_bank_account(user, account_type = "checking"):
    print("Hallo " + user + "!")
    print("Your " + account_type + " account is opened!")

open_bank_account(user = "Maria", account_type = "savings")
open_bank_account(user = "John")

Function with optional arguments

In this example we have the same open_bank_account function, but this time with three arguments. Third argument is additional_service, with default value None. This literately means that additional_service argument doesn’t have to be provided. Meaning, program will not break if we call this function with only two parameters.

Following code calls this function two times. First time function is called with two arguments and second time function is called with all three arguments. Both times, function works perfectly.

def open_bank_account(user, account_type = "checking", additional_service = None):
    print("Hallo " + user + "!")
    print("Your " + account_type + " account is opened!")
    if additional_service:
        print ("Your account includes: " + additional_service)

open_bank_account(user = "Maria", account_type = "savings")
open_bank_account(user = "John", account_type = "savings", additional_service = "Credit Card / Gold")

Quick start with Python – Python functions and return values

Quick start with Python – Function which returns a single value

This is an example of function which returns a single value. Meaning, function account_balance returns the state of our account (similar to ATM machines or mobile banking when we want to see our balance). Usually, this balance is stored in the database and getting it is not this trivial.

For simplicity reasons, we made a function which simply returns 2000 for each call, meaning everyone would have 2000 on the account. It is understandable that this function would not be a part of some real program, but it is simply used as a good example of function which returns a single value.

def account_balance():
    # this is example balance, in real life we would get it from database
    return 2000

balance = account_balance()
print(balance)

Quick start with Python – Function which returns a dictionary

Again, we have an example of very simplified get_transactions function. This function creates a dictionary (group of transactions) and returns it back to main program. In this case, we have three transactions, where positive numbers are incomes and negative numbers are representing money we have spent.

In other words, in some real case these transactions would be stored in a database. Then, we would fetch them from the database, stored into a dictionary and then returned this dictionary to main program.

def get_transactions():     
    transactions = {
        'Transaction 1 - Dentist visit': -300, 
        'Transaction 2 - Caffe Cheers': -100,
        'Transaction 3 - Salary': 3000
    }
    return transactions 

johns_transaction = get_transactions() 
print(johns_transaction)

Quick start with Python Exercise: Our Python Project

application requirements

This picture is old but gold.

Let’s quickly define our project requirements.

This is a project where we want to learn programming in Python by making a simulation of banking software.

So, we have two goals:

  • Learn Python basics
  • Make a simulation or prototype if you like, of banking system

First goal is quite straight forward. We want to go trough this complete course, check out all the examples and do all the quizzes.

Second goal, however, needs to be described in details.

Banking System – Project Requirements

Firstly, let’s define actors in our banking system:

  • Bank – represented by bank employee
  • Client – customer of a bank
  • Account – storage for finances for a customer
  • Transaction – movement of finances/money from one part of the system to the other (i.e. from one customer to the other customer)
  • System Administrator – person responsible for proper function of system, security, events inside of the system, etc.

Secondly, let’s make a requirements in form of statements. For this, we will imagine that each actor (user) of the system has a requirement (a story) which we need to implement in our software.

Here is a couple of requirements/stories which describe what do we want to do if we are a bank (meaning bank employee):

  • As bank employee, I want to be able to create new clients in our system.
  • As bank employee, I want to be able to delete or close current clients in our banking system.
  • As bank employee, I want to be able to create new accounts (banking accounts)
  • As bank employee, I want to be able to delete existing banking accounts.
  • As bank employee, I want to be able to assign client to some account (to assign ownership).

Now, if we are using our software as a Client, this is what we want to do:

  • As client, I want to be able to login to banking system.
  • As client, I want to be able to logout from banking system.
  • As client, I want to be able to change my email.
  • As client, I want to be able to make transfers between accounts.
  • As client, I want to be able to withdraw money from my account (using ATM for example).
  • As client, I want to be able to make deposit to my account.

Finally, as system administrator or security auditor, this is what we want do to:

  • As system administrator, I want to be able to examine events (logs) inside of the system.

Now, when we defined requirements for our software, let’s continue with the next lesson and write technical specifications for these requirements.

Quick start with Python – Technical Specification

As we mentioned earlier, we want to build a bank core system based on Python.

  • It is important to understand that this is an oversimplified example, optimized for our learning purposes.
  • Real life banking core system would be more advanced and would pay much more attention to security of transactions.
  • This lesson has a technical specification of project that we are building.

There are various of ways to represent structure of information systems:

  • Use Case diagrams – High abstract diagrams, which are used to represent use cases for our information system
  • Activity diagrams – These are flow diagrams, which demonstrate how information travels trough our system
  • Class diagrams – Diagrams which represents the structure of our program/code (which entities we have, how do we describe them and which functions we implement)
  • Database diagrams – Also known as Entity Relations (ER diagrams, if we use relational databases such as MsSQL, MySQL, etc.)

Since we are working on a program and our main focus is creating a code in Python, we will focus on a class diagram.

This diagram is a plan which we made before we started coding.

This is how we would like to make our program.

Quick start with Python - Bank Class Diagram
Bank Class Diagram

Let’s see how this logic should work:

  • Bank – This class is in charge of main bank logic. This is where we want to have code to add new clients to bank, to remove client. Furthermore, this is where we want to create and delete accounts. Finally, this is where we want to calculate credits, debts, etc.
  • Client – This class is in charge of clients. We will use it to implement basic client functionalities such as login, logout, change email, request for closing account, etc.
  • ClientCollection – Collection classes are very important classes in our use case. In real life this class would have a direct contact with database where all client accounts are stored. That is why we call it Client Collection. In our simplified case we will keep data inside of the Class. So, whenever we want to get something from database or put something to database, we will get it from collection and put it in collection.
  • Account – This class is in charge of accounts. Account is described with account_number (which will be unique), account_type, account_owner (client who owns the account). We also have a balance, status of the account. Furthermore, account can be active or inactive. In terms of functionality we can assign owner to account, we can activate or deactivate the account. We can update balance and much more. So yes, this class is very useful.
  • AccountCollection – Similar to ClientCollection class, this is a place where we will keep all the accounts.
  • Transaction – This is a class for a single transaction. Transaction is described by id, account where this transaction is going, date of the transaction, amount and note (text that goes with transaction). Now, in banking systems we have different types of transactions, and that is why we will make a children of this class (this is called inheritance, but we will learn about it later). For now, just think about it in a way that we want to make Transaction class more specialized.
    • Deposit – special type of transaction where we are adding money to our account. Example of deposit is when you go to the bank, take some money and put it on your account.
    • Transfer – special type of transaction where money goes from one account to the other. Most of the payments are transfers. For example, when you payed for this course that was one transaction. If you got this course for free, there was no transfer, as simple as that.
    • Withdrawal – special type of transaction where you take money form your account. Standard example of this is when you visit ATM before going out to a bar with your friends and withdraw some money from ATM to your wallet.
  • Log – whatever happens in banking system should be somehow logged. All of the above things (creation of account, transfers, new clients, old clients, deposits, withdrawals) should be inside of the logs. There are lots of things related to this (security, encapsulation, filtering, storing, timestamps). We will go trough some of these things and we will learn them parallel with Python language.
  • LogCollection – same as ClientCollection and AccountCollection.