1 of 27

An Introduction to Python�A general-purpose, easy-to-use open-source Programming Language

Telefon: +43 3842 402 - 1901 �Email: teaching@ai-lab.science

Univ.-Prof. Dr. Elmar Rueckert�

WO AUS FORSCHUNG ZUKUNFT WIRD

Chair of Cyber-Physical-Systems

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

2 of 27

Topics of this tutorial

2

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

3 of 27

What is Python?

3

  • Python is a general purpose programming language.
  • Python was invented by Guido van Rossum starting in 1989 as an easy-to-use open-source language.
  • Python supports object-oriented concepts and since 2000 it uses a Garbage-Collector for the memory management.
  • Python uses the feature Indentation to structure the code:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

4 of 27

Why Python?

4

  • Easy-to-use and open-source.
  • Many tutorial and online resources, e.g., https://pythonbasics.org/.
  • Python is the most popular programming language, see the statistics from 2019-2020 on the right.
  • We use Python together with the Robot-Operating-System (ROS) to re-use algorithms with different sensors, actuators or robots.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

5 of 27

Topics of this tutorial

5

1. What is Python?

2. Why should you learn Python?

3. Installation Instructions.

4. Structure of Python files and the __name__ attribute.

5. Clean Coding Principles.

6. Learning by Doing: Literature.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

6 of 27

Installation Instructions

6

  • GNU / Linux:
    • Python is typically pre-installed. Check your version typing python -V in the command line.
  • Mac OS:
    • Python 2.x is pre-installed. Python 3.x can be installed using Homebrew for example. Check your version typing python -V in the command line.
  • Windows:
    • Download a 32 or 64 bit Windows installer from https://www.python.org/downloads/windows/
    • During the installation, make sure to check the box to add the location python.exe to your path.
    • Alternatively, add adapt the path manually.
  • Test your Installation:
    • Open a Terminal and type: python3
    • Type print("Hello World") and press ENTER
    • Type 3+7 and press ENTER
    • Run �import sys

print("Current version of Python is ", sys.version)

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

7 of 27

Installing Packages

7

  • In PyCharm (here is a guide):
    • When creating a new project, select virtual environment for the packages.
    • After adding an import command to your code file, an error will appear.
    • Click on the error symbol and select install package.
  • Manually using conda or PIP (here is a guide):
    • Type pip install numpy in a terminal. You may want to do that in a python environment to avoid installing wrong package versions for your python version.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

8 of 27

Array / Matrix Calculus Support

8

Per default python does not support array or matrix operations or functions. Install NUMPY for that.

Some NUMPY Features:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

9 of 27

Topics of this tutorial

9

1. What is Python?

2. Why should you learn Python?

3. Installation Instructions.

4. Structure of Python files and the __name__ attribute.

5. Clean Coding Principles.

6. Learning by Doing: Literature.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

10 of 27

Structure of a Python File

10

Line 1: The shebang command denoting which Python Interpreter version is required.

Line 8-11: Some informative description of what this file is doing.

Line 13-16: List of all imported packages (sys and numpy) and also of all imported modules (e.g., using import my_file_two)

Line 18-20: Definition of a function without any arguments.

Line 18-20: Definition of a function with one argument.

Line 28-33: Main section of the code. The interpreter assigns the name ‘__main__’ to the executed script when you execute python main.py

Line 34-38: First the two function calls are executed, followed by the creation of an array. In line 38, the array is printed in the output window.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

11 of 27

Topics of this tutorial

11

1. What is Python?

2. Why should you learn Python?

3. Installation Instructions.

4. Structure of Python files and the __name__ attribute.

5. Clean Coding Principles.

6. Learning by Doing: Literature.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

12 of 27

Clean Coding Principles

12

Clean code is a set of rules and principles that helps to keep our code readable, maintainable, and extendable. It's one of the most important aspects of writing quality software. We (developers) spend way more time reading the code than actually writing it, which is why it's important that we write good code.

Writing code is easy, but writing good, clean code is hard.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

13 of 27

We follow the PEP 8 (Python Enhancement Proposal)

13

PEP 8 naming conventions:

  • class names should be CamelCase (MyClass)
  • variable names should be snake_case and all lowercase (first_name)
  • global variable names should be avoided, however use all upper_case (MY_GLOBAL_COUNTER)
  • function names should be snake_case and all lowercase (quick_sort())
  • constants should be snake_case and all uppercase (PI = 3.14159)
  • modules should have short, snake_case names and all lowercase (numpy)
  • single quotes and double quotes are treated the same (just pick one and be consistent)

# This is bad

# represents the number of active users

au = 55

# This is good

active_user_amount = 55

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

14 of 27

We follow the PEP 8 (Python Enhancement Proposal)

14

PEP 8 line formatting:

  • indent using 4 spaces (spaces are preferred over tabs)
  • lines should not be longer than 79 characters
  • avoid multiple statements on the same line
  • top-level function and class definitions are surrounded with two blank lines
  • method definitions inside a class are surrounded by a single blank line
  • imports should be on separate lines

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

15 of 27

We follow the PEP 8 (Python Enhancement Proposal)

15

PEP 8 whitespace:

  • avoid extra spaces within brackets or braces
  • avoid trailing whitespace anywhere
  • always surround binary operators with a single space on either side
  • if operators with different priorities are used, consider adding whitespace around the operators with the lowest priority
  • don't use spaces around the = sign when used to indicate a keyword argument

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

16 of 27

We follow the PEP 8 (Python Enhancement Proposal)

16

PEP 8 comments:

  • comments should not contradict the code
  • comments should be complete sentences
  • comments should have a space after the # sign with the first word capitalized
  • multi-line comments used in functions (docstrings) should have a short single-line description followed by more text

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

17 of 27

Examples

17

# This is bad

# represents the number of active users

au = 55

# This is good

active_user_amount = 55

Naming Conventions:

# This is bad

c = 5

d = 12

# This is good

city_counter = 5

elapsed_time_in_days = 12

Use descriptive names:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

18 of 27

Examples

18

from datetime import datetime

# This is bad

genyyyymmddhhmmss = datetime.strptime('04/27/95 07:14:22', '%m/%d/%y %H:%M:%S')

# This is good

generation_datetime = datetime.strptime('04/27/95 07:14:22', '%m/%d/%y %H:%M:%S')

Use pronounceable names:

# This is bad

fna = 'Bob'

cre_tmstp = 1621535852

# This is good

first_name = 'Bob'

creation_timestamp = 1621535852

Avoid using ambiguous abbreviations:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

19 of 27

Examples

19

# This is bad

client_first_name = 'Bob'

customer_last_name = 'Smith'

# This is good

client_first_name = 'Bob'

client_last_name = 'Smith'

Use consistent vocabulary:

import random

# This is bad

def roll():

return random.randint(0, 36) # what is 36 supposed to represent?

# This is good

ROULETTE_POCKET_COUNT = 36

def roll():

return random.randint(0, ROULETTE_POCKET_COUNT)

Don’t use magic numbers:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

20 of 27

Examples

20

# This is bad

class Person:

def __init__(self, person_first_name, person_last_name, person_age):

self.person_first_name = person_first_name

self.person_last_name = person_last_name

self.person_age = person_age

# This is good

class Person:

def __init__(self, first_name, last_name, age):

self.first_name = first_name

self.last_name = last_name

self.age = age

Use Constructors and avoid redundancies:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

21 of 27

Examples

21

# This is bad

def fetch_and_display_personnel():

data = # ...

for person in data:

print(person)

# This is good

def fetch_personnel():

return # ...

def display_personnel(data):

for person in data:

print(person)

Functions should only perform a single task:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

22 of 27

Examples

22

# This is bad

def render_blog_post(title, author, created_timestamp, updated_timestamp, content):

# ...

render_blog_post("Clean code", "Nik Tomazic", 1622148362, 1622148362, "...")

# This is good

class BlogPost:

def __init__(self, title, author, created_timestamp, updated_timestamp, content):

self.title = title

self.author = author

self.created_timestamp = created_timestamp

self.updated_timestamp = updated_timestamp

self.content = content

blog_post1 = BlogPost("Clean code", "Nik Tomazic", 1622148362, 1622148362, "...")

def render_blog_post(blog_post):

# ...

render_blog_post(blog_post1)

Use Classes to keep the number of arguments at a minimum:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

23 of 27

Examples

23

# This checks if the user with the given ID doesn't exist.

if not User.objects.filter(id=user_id).exists():

return Response({

'detail': 'The user with this ID does not exist.',

})

As a general rule, if you need to add comments, they should explain "why" you did something rather than "what" is happening:

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

24 of 27

Hints: Use Context Manager to read files

24

with open('wisdom.txt', 'w') as opened_file:

opened_file.write('Python is cool.')

# opened_file has been closed.

Read files using the ‘with’ statement:

file = open('wisdom.txt', 'w')

try:

file.write('Python is cool.')

finally:

file.close()

Avoid

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

25 of 27

Topics of this tutorial

25

1. What is Python?

2. Why should you learn Python?

3. Installation Instructions.

4. Structure of Python files and the __name__ attribute.

5. Clean Coding Principles.

6. Learning by Doing: Literature.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

26 of 27

Learning by Doing

26

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS

27 of 27

Thank you for your attention!

Univ.-Prof. Dr. Elmar Rückert

Chair of Cyber-Physical-Systems

Montanuniversität Leoben

Franz-Josef-Straße 18,

8700 Leoben, Austria

Phone: +43 3842 402 – 1901 (Sekretariat CPS)

Email: teaching@ai-lab.science

Web: https://cps.unileoben.ac.at

27

Disclaimer: The lecture notes posted on this website are for personal use only. The material is intended for educational purposes only. Reproduction of the material for any purposes other than what is intended is prohibited. The content is to be used for educational and non-commercial purposes only and is not to be changed, altered, or used for any commercial endeavor without the express written permission of Professor Rueckert.

MONTANUNIVERSITÄT LEOBEN

CYBER-PHYSICAL-SYSTEMS