This is an old revision of the document!


Python3 Crash Course

Command Line (CLI)

Start REPL (Read Execute Print Repeat) interactive mode and exit:

shell$ python # OR python3
>>> 
>>> quit() # OR CTRL-D
shell$

Execute files:

shell$ python filename.py
shell$ python filename.py arg1 arg2 arg3
shell$ python -i filename.py # start in interactive mode

Basics

Variables and numerical data types:

a = 10   # int
b = 10.2 # float

Strings and string formatting:

s1 = "Ana are mere"
s2 = """This is a
multiline string"""
age = 20
s3 = f"Ana are {age} ani"

Functions:

def my_function(a, b):
    return a + b

!Note: In Python we don't use curly braces. Instead, we use indentation to define the scope of a function/statement.

Input/Output

Standard I/O:

input_text = input() # type str
print(input_text)
a = input()  # 10
a = int(a)   # convert to int
print(a + 5) # 15

Files:

f = open("path/to/file.txt") # default behaviour is 'read text'
data = f.read() # reads the entire file in a string
lines = f.readlines() # reads the lines in a list
f.close()
 
# when using the 'with' statement no need to close the file
# 'w' - write, 'r' - read, 'a' - append, 'x' - create
# 't' - text, 'b' - binary
with open("result.txt", 'w') as f: # 'write text'
    f.write(data)
    f.writelines(lines)

Operators & Flow Control

  • +, +=, -, -=, *, *=, /, /=
  • ==, !=, <, ⇐, >, >=
a = 7 // 2 # a = 3 (Integer Division)
b = 7 % 2  # b = 1 (Modulus)
c = 2 ** 3 # c = 8 (Exponent)
d = 1 ^ 0  # d = 1 (XOR operation)

Conditional Statements & Loops

We can use most of the keywords from C:

i = 0
cnt = 0
while i < 100:
    if i == 25:
        continue
    if i < 50:
        cnt += 1
        if i % 2 == 0:
            cnt *= 2
    elif i >= 50 and cnt % 2 == 0:
        cnt += 3
    else:
        cnt -= 1
        if i > 90 or cnt > 200:
            break

!Note: We use 'and' and 'or' to combine 2 logical statements.

Data Structures

Lists:

l1 = [1, 2, 3]
l1.append(4) # [1, 2, 3, 4]
l1.reverse() # [4, 3, 2, 1]
e1 = l1.pop()  # l1 = [4, 3, 2], e1 = 1
e2 = l1.pop(0) # l1 = [3, 2], e2 = 4
l1.extend([10, 12, 15]) # l1 = [3, 2, 10, 12, 15]
l2 = l1[:] # copy the entire list into l2
c1, c2, c3 = l1[:1], l1[1:3], l1[3:] # c1 = [3], c2 = [2, 10], c3 = [12, 15]
c1.insert(0, 2) # c1 = [2, 3]
c1.remove(3) # c1 = [3]

Dictionaries:

dictio = {}
dictio["key1"] = 1
"key1" in dictio # True
"key2" not in dictio # True
del dictio["key1"]
dictio.clear() # deletes all entries in the dictionary

Tuples:

t = (1, 2, 3) # same as lists, but immutable

Sets are like dictionaries in terms of complexity, but they store only the “keys”.

s = {1, 2, 3}
2 in s # True O(1) time complexity

Object Oriented Programming

class MyClass:
    def __init__(self, arg1, arg2): # constructor
        self.arg1 = arg1 # object properties
        self.arg2 = arg2
 
    def my_method(self, arg1, arg2): # class method
        self.arg1 += arg1
        self.arg2 -= arg2
        return self.arg1 * self.arg2
 
 
obj1 = MyClass(1, 2)
result = obj1.my_method(2, 3)
print(result)

Built-in Functions

range(start, stop, step)
for i in range(5):
    print(i) # 0 1 2 3 4
 
for i in range(3, 10, 2):
    print(i) # 3 5 7 9

In Python 2.x range() generates first the entire list of numbers and then iterates through it.

for i in range(5): # equivalent to: for i in [0, 1, 2, 3, 4]

The alternative is the xrange() function which uses a generator to generate numbers as you need them. Python 3.X range() function is the xrange() function from Python 2.x.

def xrange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step
 
iter = xrange(0, 10, 1)
type(iter) # <class 'generator'>
enumerate()
for index, value in enumerate([10, 20, 30]):
    print(index, value)
 
for key, value in enumerate({"key1": "val1", "key2": "val2", "key3": "val3"}):
    print(key, value)
len()
len([1, 2, 3]) # 3

Other useful Built-In functions: abs(), all(), any(), max(), min(), zip(), type(), sum(), str(), chr(), ord(), sorted(), round(), reversed(), int(), float()

Comprehensions

List comprehension:

l1 = [2*i if i % 2 == 0 else 3*i  for i in range(100)] # [0, 3, 4, 9 ...]
l2 = [f"item{i}" for i in range(100)] # ["item0", "item1", ..., "item99"]
l3 = [0 for i in range(100) if i % 2 == 0] # len(l3) = 50

Dictionary comprehension:

d1 = {f"key{i}": i*2 for i in range(100)}

References

ic/resurse/python.1601642014.txt.gz · Last modified: 2020/10/02 15:33 by acosmin.maria
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0