Python Studies: Crash Course
Crash Course Notes
Hope I can do it very quick, just to get similarities and deltas to other languages and catch the main idea of programming in Python.
2023-01-02
Data Types and Variables
- case sensitive,
- no number in the beginning
- no code words like while, if …
- using snake coding possible: Snake_Part1_Part2
- chained assignment pissible:
>>> a = b = c = 300 >>> print(a, b, c) 300 300 300
- Numeric
- Integer, can be on anny length
user_salary = 5000
- Float 15 digit precision to 15’th decimal place, indicated by “.”
number_float = 2.0Attention: float has some quirks due limited precision. Will affect comparisions:>>> 0.3 + 0.1 0.4 >>> 0.1 + 3.8 3.9 >>> 0.1 + 0.2 0.30000000000000004
Solutions:
- Using decimal module, providing support for decimal floating-point arithmetic like fixed precision.
- Higher precision: Use NumPy, a scientific computing library for Python. NumPy module provides a data type numpy.float128
- Round the floats
- Complex Numbers (same about precision like float).
complex_number = 1 + 1j - Boolean (true / false) –> mention: False or True
my_bool = False # or True - binary: “0b” –> 0b0101
- ocatal: “0o” –> 0o01234567
- hex: “0x” –> 0x00FFPrint binary / ocatal / hex) using built-in function
Built-in function bin(), oct(), hex()
Built-in function format(), string method str.format(), f-strings
if not –> will be printed as integerprint(bin(my_variable)) #--> binary print(oct(my_variable)) #--> octal print(hex(my_variable)) #--> hex
- String (Unicode characters)
- List – in order, not fixed, different types
- Tuple – in order, fixed list, different types
- Dictionary – not in order, different types, keys different types, but must be irreversible
dict = {1:’cat’, 2:’dog’}
dict = {‘place’: ‘New York’, 1:[3,6,9]}also with dict()
dict = ({1:’cat’, 2:’dog’}) - Set – not arranged in any particular sequence, can be modified
- Integer, can be on anny length
2023-01-03
IDLE and Python Shell
- IDLE is good to learn python, but not for larger projects. Actual I prefer “Visual Studio Code”
- installing idle (but should already)
- IDLE has 2 main windows:
- Shell Window (fire up when start)
- Editor Winwdo (via edit new file in shell window)
you can open as many file windows you want - in console just open [python] (or python3] and also sehll will start. Hint (so there like [python3] and [python] is most equal):$ sudo apt install python-is-python3
- running python scripts (there also a lot of command line parameters):$ python3 $script.py
- IDLE has also an debug mode and other features. See IDLE tutorial.
Operators in the Python language
Operators in Python are separated into following categories.
Operator quick view / Cheat Sheet:
- Arithmetical Operators
- Logical Operators
- Comparison Operators
- Assignment Operators
- Bitwise Operators
- Special Operators
Details in the Operator Cheat Sheet ore more detailed in:
- The Real Python Tutorials – Operators
- Python Notes – The operator module in Python
- educba.com – Operators
2023-01-04
Numbers in Python:
- Real Python – Numbers in Python
- Integer
- Binary, Octacl, Hex, are all valid representations of integers. How to convert
- Float (precission issue).3e500 will be infinite (at most systems)
>>> f=3e500 >>> f inf
convert string to float:
>>> float('3.5') 3.5
Complex, required to utilize letter j or J as imaginary component. All other will lead to an syntax error (like “k”). Also “i” for the real part is not allowed.
Strings
Outlook:
Methods in Python. Methods are very similar to functions, but in Python a functionm, part of an object (like the data objects of a string, but also others). Is not restricted to classes instances.
In Python every data type comes with a collection methods
2023-01-05
Flow Control in Python
basically 3 types of control flows:
- Sequencing – no flow control
- Selection – typical ‘if’ statement
- Repetion – ‘for’ and ‘while’
Decision control or branching statement. Python is following the off-side-rule
If one branche is not in use yet – using the “pass“ Statement as a placeholder – aka “how to do nothing in Python”. This also works for empty functions, classes…
‘if’ statement
- if & if-else
if(condition): # execution this block if condition is _True_ else: # execution of this block if condition _False_
- if-else-elif, for making number of choices
if condition_1: # condition_1 execution this block if condition_1 is true elif condition_2: # condition_2 execution this block if condition_2 is true elif condition_3: # condition_3 execution this block if condition_3 is true ... else: # execution of this block if non of the conditions are true
Wrapping conditions like “(< condition >)” are possible & don’t forget the “:“.
Nesting:
Each execution block itself can contain a new if statement. But should be avoided due high potential of confusion.
Repetition loops ‘while’ & ‘for’
‘while’ loop
- indefinite iteration: Block executing as long as some condition is met.
- definite iteration: Number of times the designated block will be executed is specified explicitly at the time the loop starts.
- break & continue statements (break & continue are Python keywords).
- of course, break or continue statement should be combined with an if statement…
while (expression) # statement_1 # statement_2 # ... # statement_n break # --> will leave the loop # statement_n+1 # statement_n+2 continue # --> will go back to while (expression) # statement_n+3 # ... # break will continue here
Attention: Python doesn’t have a ‘do-while’ construct. But can be emulated with the break statement.
‘for’ loop
Attention this is very different from other languages I know (e.g. C). Python is using iterable objects and Interger is not iterable. Need to be converted by ‘range()’ function but is therefore much more flexible and object orientated.
Iteralbles & Iteration, definitions:
Term | Meaning |
---|---|
Iteration: | looping process through the objects, collection |
Iterable: | Object that can be iterated |
Iterator: | Object that produces successive items |
or values from its associated iterable | |
iter(): | Built-in function used to obtain an |
iterator from an iterable, go to next iterabel | |
Attention: can’t go back, no “prev() iterator! |
- Iterable with iter():
- String
- List
- Tuple
- Set
- Dict
- Not iterable with iter():
- Integer
- Float
- Built in functions
Many objects can be designed to be iterable (e.g. open files or other I/O operations). Most objects in Python can be made iterable, including user defined ones.
The most basic code itself is very simple:
for var in iterable:
# Execute this block
else:
# Do this block
# continue (e.g. after a finishing loop or break condition
An very simple Example:
a = ['aaa', 'bbb', 'ccc']
for i in a:
print(i)
will get this output:
aaa
bbb
ccc
Using ‘break’ and ‘continue’ statements:
‘break’ and ‘continue’ work similar way like the ‘while’ loop. ‘break’ terminates the loop completely and proceeds to the first statement following the loop.
Attention:‘break’ will override the “else:” part.
Using range()
With ‘range()’ function I can iterate through Integer “ranges”.
range(stop) # 0 ... stop
range(start, stop) # start ... stop
range(start, stop, step) # start ... stop by step increment
- in case of integer start could also be negative
- of course not only integers can be used, mostly(?) all Iterables too.
Key words
There are actual 35 Keywords in Python. See also Python Reference.
False | class | from | or | |
None | continue | global | pass | |
True | def | if | raise | |
and | del | import | return | |
as | elif | in | try | |
assert | else | is | while | |
async | except | lambda | with | |
await | finally | nonlocal | yield | |
break | for | not |
2023-01-06
Functions – basic overview
- calling a function is also known as invoking a function
- Argument: value sent to the function when it is called
- Two major types:
- Built in Functions:
–> Overview @Python.org - Custom or user defined functions:
–> Tutorial @ Real Python about user-defined functions
- Built in Functions:
- Inside the custom functions I can define local variables, outside defined variables are named global variables
- there is also namespace separation (inside function I can use same variable names and identifiers. Except the ones I defined as global variables.–> Real Python @ Basics about namespace separation
–> Real Python @ Main articel about namespace and Scope
- there is also namespace separation (inside function I can use same variable names and identifiers. Except the ones I defined as global variables.–> Real Python @ Basics about namespace separation
- Typecasting: Using the right types (depending on the return of the build in and custom functions).
As example, the built in input() function will handle input as string:x = input("Number 1:") # e.g.: 8 y = input("Number 2:") # e.g.: 9 s = x + y print(s) # result will be 89
so adding typecasting before print(s):
x = input("Number 1:") # e.g.: 8 y = input("Number 2:") # e.g.: 9 s = int(x) + int(y) # typecasting x and y print(s) # result will be correct: 17
Functions – User defined
- Syntax:
def _function_name_ ([_parameters_]): _statement(s)_
Component | Meaning |
---|---|
def | keyword, function is being defined |
function_name | valid Python identifier, names the function |
parameters | optional, comma-separated list of parameters |
: | denotes the end of the Python function header |
statement(s) | Python statements doing the function |
return | a stating passing back data, be aware about type |
- parameter vs. argument
parameters behave like local defined variables, like the ones defined locally inside the function, the argument is the content of this parameters.
–> Real Python @ Argument Passing - return Statement @ Real Python
- pre define the parameters and also return statement type:
def f(a: int = 12, b: str = 'baz') -> float: print(a, b) return(3.5)
- starting with Python3 Python Function Annotations:
Providing a way to attach metadata to function’s parameter.
–> Real Python @ function annotation
- do nothing with the function or execution of the function
–> Annotionas are nothing more than dictionaries of metadata - good for documentation
- good for type checking
- good for automated tools parsing code
- can be modified dynamically for counting how often function was called
- add documentation with docstrings.
- starting and ending with tripple-quote
... """ single line Docstring """ ... """ Multi line Docstring"""
- Docstrings are accessible inside Python with the expression:
_function_name_.__doc__.
Sets in Python – basic overview
- A collection of things, not arranged in any particular sequence is a set.
- Sets are unordered.
- Set elements are unique. Duplicate elements are not allowed.
- A set itself may be modified, but the elements contained in the set must be of an immutable type.
- can be created with built-in function set(), this will also avoid duplicates, but still unordered and the original order is not preserved.
- most basic:
x = set(_iter_)
- example:
s = 'quux' list(s) '>>> ['q', 'u', 'u', 'x'] set(s) {'x', 'u', 'q'}
- Sets, more detailed @ Real Python:
Lists and Tuples and Dictionary in Python – basic overview
- the most important, versatile und useful data types in Python
- List
- Lists are ordered.
- Lists can contain any arbitrary objects.
- List elements can be accessed by index.
- Lists can be nested to arbitrary depth.
- Lists are mutable.
- Lists are dynamic.
- Tuple are most similar to list, beside:
- Are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
- Tuples are immutable. They can’t be modified. So why use?
- Program execution is faster when manipulating a tuple.
- If data don’t want to be modified.
- Data type Dictionary need one of its components a immutable value. List is not working for that, but tuple.
- Dictionary
- Dictionaries and lists share equal characteristics for:
- mutable
- dynamic, can grow and shrink as needed.
- can be nested. A list can contain another list.
- A dictionary can contain another dictionary.
- A dictionary can also contain a list, and vice versa.
- Dictionaries differ from lists by how elements are accessed:
- List elements are accessed by indexing
- Dictionary elements are accessed via keys.
- Dictionaries and lists share equal characteristics for:
Modules and Packages in Python – basic overview
Modules and Packages allow modular programming. Advantages:
- Simplicity
- Maintainability
- Reusability
- Scoping
A module can be written in
- Python (of curse)
- in C
- there are built-in modules
Modules are imported by ‘import’ statement
import 'module'
Package is ‘packaging’ modules itself.
– grouping and organizing Modules.
– allows hierarchical structuring of the module namespace, using dot notation.
– help avoid collisions between module names
Conclusion
Now I got a very basic idea about Python. No, I can’t code Python right now. This will be start in the next quests over the next month in 2023.
I can currently only hope that I have enough free time (less overtime @ work) and energy to follow this path.
But at least – now I have a basic idea of this programming language.