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
Topics of this tutorial
2
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
What is Python?
3
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
Why Python?
4
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
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
Installation Instructions
6
print("Current version of Python is ", sys.version)
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
Installing Packages
7
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
Array / Matrix Calculus Support
8
Per default python does not support array or matrix operations or functions. Install NUMPY for that.
Some NUMPY Features:
See https://pythonexamples.org/numpy/ for details.
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
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
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
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
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
We follow the PEP 8 (Python Enhancement Proposal)
13
PEP 8 naming conventions:
# This is bad
# represents the number of active users
au = 55
# This is good
active_user_amount = 55
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
We follow the PEP 8 (Python Enhancement Proposal)
14
PEP 8 line formatting:
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
We follow the PEP 8 (Python Enhancement Proposal)
15
PEP 8 whitespace:
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
We follow the PEP 8 (Python Enhancement Proposal)
16
PEP 8 comments:
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
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
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
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
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
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
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
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
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
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
Learning by Doing
26
MONTANUNIVERSITÄT LEOBEN
CYBER-PHYSICAL-SYSTEMS
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