Python 3 Refresher — Part 1
1. Print output to console
>> print(Python is the best!')
2. Common data types
Numbers
- Integers e.g. 5
- Floats e.g. 5.431
- Complex numbers e.g. 1 + 3j
Strings
- “Á string is a sequence of characters’’
Each of these data types support a number of common operations:
>>> 'hello' * 3 # output: hellohellohello>>> 'hello' + 3 # Error>>> 'hello' + str(3) # hello3>>> 8 / 1 # 8.0>>> 8 // 1 # 8>>> 8 // 1.0 # 8.0>>> 1 + 3j.real # 1.0
3. Abstract data types — data model defined by behavior
List
- Collection of ordered items e.g. [ ‘USA’, ‘UK’, ‘RSA’]
- Members can be any valid python data types
Set
- Can only contain unique item e.g. [ 1,5,2]
Tuples
- Cannot be changed once initialized e.g. (4,3)
Dictionary or hasmap
- Store data as key:value pairs
- e.g. { ‘ndamu’: 098 221 2314 }
4. String formatting
- Used to populate placeholders with actual values during code execution.
>>> print('Her name is %s. She is %d years old' %('lili', 3)) # Her name is lili. She is 3 years old
- % s — Strings or objects that can be represented as strings
- %d — Integers or non-decimal numbers e.g. 7
- %.<x>f — Floating point number with x number of digits after the dot
- %x — Hexadecimal numbers
5. Classes
- Define the characteristics and behavior of objects
class Vehicle:
def __init__(self, name, make, year=2019):
name = self.name
make = self.make
year = self.year def accelerate:
print('Increasing speed')# Instantiate car object
>>> bmw = Vehicle('BMW', 'M6', 2012)>>> print( bmw.make )
# M6
6. Modules and packages
- Any python file with a dedicated function is module , e.g. draw.py
- A module or part of a module can be imported to a project using the following syntax
>>> import draw>>> from draw import draw_polygon
- A collection of modules in a directory is called a package.
- This directory must contain a file called __init__.py for python to treat it as a module.