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 Data Types:

a = 10   # int
b = 10.2 # float
c = "Ana are mere" # str

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"]

Tuples:

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

Sets:

 

Object Oriented Programming

class 

Built-In functions

  • range()
  • len()
  • type()

===

String formatting

Old way: % - format OR str.format() New way: F-strings

string = f"Ana are {nr_mere} mere."

Conditions & Loops

i = 0
cnt1 = 0
while i < 10:
    if i%2 == 0:
        cnt += 1
 
 range(), len(), type()

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'>

References

ic/resurse/python.1601378493.txt.gz · Last modified: 2020/09/29 14:21 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