Whetting Your Appetite
-
There are some tasks that you’d like to automate. E.g.:
-
Rename and rearrange a bunch of photo files in a complicated/simple way.
-
Or search and replace over a large number of text files.
-
-
Do not like write/compile/test/re-compile cycle.
This can save us the precious little time we’ve got ;).
We can do all of these things with Python.
[!TIP]
Wanna learn coding in Python. You can go and read their standard modules. It can give you a very good sense of direction and how you should think when you develop an app.
[!TIP]
Whenever you got stuck somewhere go and chat with Generative AI tools. E.g. ChatGPT.
Python REPL
Use it:
- To experiment with features of the language.
- To write throw-away programs.
- To test functions during bottom-up program development.
-
As a handy desk calculator : .
The road ahead us
- Simple expressions.
- Statements and data types.
- Functions and modules.
- Exceptions and user-defined classes.
Ref
YouTube/Aparat
Invoking the Interpreter
- We talked about how to install Python here.
- And we know how to run it thanks to our first exposure to VSCode.
- Exit from interpreter using end-of-file character:
Ctrl + d
on Unix,ctrl + z
on Windows.- Or just type
quit()
.
-
In REPL we have:
-
Code completion.
- On Windows you need to install
pyreadline3
:python -m pip install pyreadline3
(ref).
- On Windows you need to install
-
history substitution.
-
-
Operates somewhat like the Unix shell:
-
Called with standard input connected to a tty device? It reads and executes commands interactively.
-
Called with a file name argument or with a file as standard input, it reads and executes a script from that file.
-
Use
-c
flag to tell python interpreter that it needs to run the specified code:
-
- Commands are read from a tty.
- Primary prompt:
>>>
. - Secondary prompt/Continuation lines:
...
.
-
# Python source files are treated as encoded in UTF-8 (learn more about encoding).
# -*- coding: encoding -*-
You can see a list of them here.
YouTube/Aparat
Ref
How computer memory works
- Our memory defines us.
- You’re past exps.
- Know-hows.
- etc.
- Computers are the same in that regard.
- In computers everything takes the form of what is commonly referred to as bits.
Bit
- Stands for binary digit.
- Can switch between 0 and 1.
- Every file/software consist of millions of these bits.
- Each one of them is stored in a memory cell.
CPU – Central Process Unit
- Computer’s brain.
-
Process bits.
- The amount of bits needs to be processed grows. Thus the need to always even in the modern era to optimize your software.
Short-term memories
- Needs to be fast, thus we can access any place of the memory in any order.
- When we run a program CPU allocates memory to that program in short-term memory to run that program.
- E.g. When you open a movie it needs to process bits of data and tell your monitor what to do. In order to do that it needs to put your video’s info somewhere withing reach and that somewhere is short-term memories.
- Used to store data just for a short period of time.
- Cut of the power supply (electricity) and your data is gone.
- Categories:
- DRAM – Dynamic Random Access Memory.
- Cache – Internal cache inside CPU made up from SRAM (Static RAM).
Long term memories
-
Most well know ones:
- Optical base storages:
- DVD – Digital Versatile Disc.
- CD – Compact Disc.
-
HDD – Hard Disk Driver.
-
Magnetic storage.
-
- SSD – Solid State Drive.
- USB hard disk driver.
- Optical base storages:
- Used to store data permanently.
- Turn off the computer and turn it back on the next day it still has the data.
Memory latency
-
The time it takes for the bits to be transferred from memory to CPU.
Digital storage terminology
- Byte is 8 bits put together.
- The space necessary to store 1 character (letter/number/symbol).
- Kilobyte is 1000 bytes put together.
- Enough to store one third of a page.
[!NOTE]
Digital storage uses the binary system, thus everything needs to be in powers of two.
- 1000 Kilobytes.
- Roughly enough to store one book, one photo, or 1 minute of music.
- 1000 Megabyte.
- Enough for 1000 books.
Ref
- How computer memory works - Kanawat Senanan.
- Computer Skills Course: Bits, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes (UPDATED VERSION).
YouTube/Aparat
Informal introduction
- To end a multi-line command in REPL press enter twice.
-
Comments in Python:
- Start with the hash character:
#
. - Extend to the end of the physical line.
- Clarify code.
- Ain’t interpreted by Python interpreter.
- Can be omitted.
-
Don’ts:
-
Cannot write comment within a string literal.
A hash character within a string literal is just a hash character!
-
- Start with the hash character:
Python as a Calculator
- Type an expression and it will evaluate it.
-
Expression syntax:
- The operators
+
,-
,*
and/
can be used to perform arithmetic. - Parentheses (
()
) can be used for grouping.
- The operators
Numbers in Python
- Integer numbers:
- Type:
int
. - E.g.
2
,4
,20
.
- Type:
- Floating point numbers:
- Type:
float
. - Have fractional part.
- E.g.
5.0
,1.6
.
- Type:
Decimal
numbers.- Ideal for precise base-10 arithmetic.
- E.g. in financial calculations, do not have errors like:
0.1 + 0.2 != 0.3
. -
Example in Python
from decimal import Decimal decimal1 = Decimal('0.1') decimal2 = Decimal('0.2') result = decimal1 + decimal2 print(decimal1 + decimal2 == Decimal('0.3')) # True print(decimal1 + decimal2 == 0.3) # False print(0.1 + 0.3 == 0.3) # False
Computers use binary (base-2) to represent numbers. Many decimal fractions (like
0.1
and0.2
) cannot be represented exactly in binary. This results in small precision errors.print(0.1 + 0.2) # 0.30000000000000004
Fraction
numbers.- Precise representation of fractions.
- Exact rational arithmetic (e.g.,
1/3
remains1/3
instead of an imprecise float like0.333...
). -
Example in Python
from fractions import Fraction fraction1 = Fraction(1, 3) # 1/3 fraction2 = Fraction(2, 5) # 2/5 result = fraction1 + fraction2 # Fraction addition: 1/3 + 2/5 = 11/15 print(f"Fraction addition: {fraction1} + {fraction2} = {result}")
f""
is what we call "f-strings".
- Complex numbers:
- A number that has both a real part and an imaginary part.
- E.g.
3+4j
.
Operators
Name | Plus/Addition | Minus/Subtract | Multiply | Division | Floor division | Remainder/Dividend | Power | N/A |
---|---|---|---|---|---|---|---|---|
Operator | + | - | * | / | // | % | ** | Mixed |
Example | 7+3 |
7-3 |
7*3 |
7/3 |
7//3 |
7%3 |
7**3 |
7*3.2+1 |
Results | 10 |
4 |
21 |
2.3333333333333335 |
2 |
1 |
343 |
23.400000000000002 |
Operator precedence
Example:
Variables
- Assign a value to a variable with
=
. - Variable is not “defined” (assigned a value), trying to use it will give you an error.
>>> var_name Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'var_name' is not defined
- A special variable named
_
(underscore).- It holds the result of previous expression.
-
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625
- Treat it as read-only.
Strings in Python
- Manipulate text.
- Type:
str
. len
built-in function return length of a string:len(word) # 6
.- AKA “text sequence type”.
-
Enclosed in:
- Single quotes:
'...'
. - Double quotes:
"..."
.
[!NOTE]
To quote a quote:
- “Escape” it, by preceding it with
\
:'I\'m'
. - Use the other type of quote:
"I'm"
.
To escape
\
itself:- Add another
\
in front of it:\\
. - Use raw strings:
r'C:\Users\kasir-barati' r'I\'m called back slash & \ is my symbol'
- Single quotes:
- Learn how to use
\
at the end of your string:# This is invalid r"I am \"
- Use 3 quotation mark for multi line string:
- E.g.:
"""Multiline string"""
-
Have the initial newline Exclude the initial newline print(""" Hi """)
print("""\ Hi """)
- E.g.:
String Operators
*
:- Repeats it.
- E.g.:
3 * "hi "
+
:- Concatenates.
- E.g.:
"Mohammad " + 'Jawad'
.- Same as:
"Mohammad " 'Jawad'
(only works with two literals).
- Same as:
- Mix them:
- E.g.:
("-" * 5) + "I LOVE AI" + ("""-""" * 5)
- E.g.:
-
[]
:- Subscript:
- The first character’s index is 0.
- Negative indices: start counting from the right.
-
word = 'Python' print(word[0]) # P print(word[-1]) # n
- # Slicing
msg[start:end:step]
:# [0, 2) # Returns 'Py' word[0:2] # Omitted first index defaults to zero # Returns 'Py' word[:2] # Omitted second index defaults to the size of the string being sliced # Returns 'on' word[4:] # word[-2:] # Returns 'Python' word[:2] + word[2:] # Out of range slicing: # Returns 'on' word[4:42] # Out of range slicing: # Returns '' word[42:]
[!CAUTION]
>>> word[42] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
- Subscript:
Immutable Indices
word[0] = 'K' # or word[2:] = 'char'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Lists in Python
- A compound data type.
- Group together other values.
- The most versatile.
- A list of comma-separated values/items between square brackets.
- Can contain items of different types.
len
returns the length of the list.- Can be indexed and sliced.
- Mutable indices.
squares = [1, 4, 9, 16, 25]
squares[0] # 1
squares[-1] # 25
squares[-2:] # [16, 25]
squares.append(113) # [1, 4, 9, 16, 25, 111]
squares = squares + [36, 49] # [1, 4, 9, 16, 25, 111, 36, 49]
squares[-3] = -888 # [1, 4, 9, 16, 25, -888, 36, 49]
Shallow copy
books = ["Freakonomics", "The Prince", "The Pragmatic Programmer"]
my_favorite_books = books
my_favorite_books.append("The Zero Marginal Cost Society")
print(books)
Any changes to one will be seen through all other variables that refer to the same list.
books = [
"Hands-On machine learning with Keras and Tensorflow",
"Grokking Deep Learning"
]
# Here we are copying them
want_to_read = books[:]
want_to_read.append("Artificial Intelligence: A Guide for Thinking Humans")
print(books)
[!TIP]
To learn how to style your code which is widely adapted you can check PEP 8 – Style Guide for Python Code.
Multi Dimensional lists
-
2D lists:
-
3D lists:
array_3d = [ [ # Array 1 [111, 112, 113], [121, 122, 123], [131, 132, 133], ], [ # Array 2 [211, 212, 213], [221, 222, 223], [231, 232, 233], ], [ # Array 3 [311, 312, 313], [321, 322, 323], [331, 332, 333], ], ]
Our first real program in Python
I guess you know Fibonacci series.
Here is how you can code it in Python
a, b = 0, 1
while a < 10:
print(a)
a, b = b, a+b
Explanation of Python syntax used in this program
- Multiple assignment.
-
while
loop.
NOTE: In Python any non-zero integer value istrue
. zero isfalse
.
Comparison operators are:<
(less than).>
(greater than).==
(equal to)<=
(less than or equal to).>=
(greater than or equal to).!=
(not equal to).
print()
Ref
3. An Informal Introduction to Python.