Python Introduction
Python Introduction
Install Python3
1 | sudo apt install python3 |
To check python3 version
1 | python3 --version |
You can now run the python3 interpreter using python3
command.
You can create python program using text editors such as VS Code and run the python program using python3
command. VS Code has Python Extension that provides intelliSense and debugging support. You can also use PyCharm if you prefer an IDE.
print()
print objects. print() is a build-in function. print() reference
method signature
1 | print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) |
Demo
1 | print("hello python") |
Variable
- Python variables can only begin with a letter(A-Za-z) or an underscore(_).
- Python variables are dynamically-typed. Do not specify variable type when declaring one.
1 | greeting = "Hello World" |
Getting input
Use input([promp]) build-in function to get input. input reference
1 | # getting input |
To get input as int. Note that you need to use Ctrl+D to send EOF to indicate no more input.
1 | import sys |
Build-in Types
Python has 5 standard data types
- Numbers(integers, floating point numbers, and complex numbers)
- String
- Boolean(value are True or False)
- sequence types(List, Tuple, Dictionary)
Infinity
In python, you can have a number with infinity value
1 | import math |
use type() to get object type
type() is also a build-in function. type() reference
1 | type(123) # => <class 'int'> |
None
Many languages has null value. In python, the equivelent is None
. None
is the only instance of class NoneType
You can assign None
to a variable. Use identity operator is
to check if a variable has None
value.
1 | my_var = None |
Operators
Arithmetic Operator
operator | meaning |
---|---|
+ | addition |
- | subtraction |
* | multiplication |
/ | division |
// | floor division |
% | Modulus |
** | exponentiation |
Comparison Operator
operator | meaning |
---|---|
< | less than |
> | greeter than |
== | equal to |
!= | not equal to |
<= | less than or equal to |
>= | greeter than or equal to |
Assignment Operator
operator | meaning |
---|---|
= | assign |
+= | add and assign |
-= | subtract and assign |
/= | divide and assign |
* = | multiple and assign |
%= | modulus and assign |
**= | exponent and assign |
//= | floor-divide and assign |
Logical Operator
operator | meaning |
---|---|
and | return true when both statement are true |
or | return true when either statement is true |
not | inverts the Boolean value of an expresion |
Membership operator
There are two membership operators ‘in’ and ‘not in’
1 | 'tea' in ['latte', 'tea', 'coke'] |
1 | 'tea' not in ['latte', 'tea', 'coke'] |
String
- You can use single quotes or double quotes
- If the string contains single quote, then it is better to use double quotes
- tripple quotes “”” and ‘’’ can be used for multiline string
- use square brackets for slicing
- use + to concatenate strings
- use len() function to return a string’s length
- use == to compare strings
- Use
in
operator or find method to check if a string is a substring of another string
1 | s = "Hello World" |
Control Statement and Iterator
If Statement
1 | x = input("x:") |
While Statement
1 | count = 0 |
The break statement terminates the loop containing it.
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
For loop
1 | nums = [1, 3, 7, 10] |
range function
for loop with range() function.
1 | # output 0 to 4 |
range() function generate a sequence of numbers
1 | range(start, stop, step) |
Pass statement
pass
statement does nothing. It is usally used when we have a loop or function that is not implemented yet.
1 | for i in [1, 2, 3, 4]: |
List, Tuple and Dictionary
List
- ordered list
- use [index] to get the item in the list
- if the index is negative, then it will count from the right instead of left
- use in operator to check if an item is in the list
- use len() function to get the string length
- use append method to append item to a list
see https://docs.python.org/3/tutorial/datastructures.html#more-on-lists for all list operations
1 | empytList = [] # empty list |
Use List as Stack
1 | stack = [1, 2, 3] |
Queue
Using list as Queue is not efficient. Use collections.deque
because it has fast appends and pops at both ends.
1 | from collections import deque |
Tuple
Tuple - tuple is like an immutable list.
1 | numbers = (2, 4 ,6 ,8) |
Dicutionary
Dictionary - like a Map, it stores key-value pairs. Order doesn’t matter for a dictionary.
see https://docs.python.org/3/tutorial/datastructures.html#dictionaries for all dictionary operations
1 | employees = { "alice": "developer", "bob": "sales" } |
Function
Functions are defined using ‘def’
1 | def add(num1, num2): |
Python supports multiple return values.
1 | def cal(num1, num2): |
Files
By default, files are open in reading mode. modes are ‘r’, ‘w’, ‘x’(exclusive creation), ‘a’, ‘b’, ‘+’(reading and writing).
read file and write file.
1 | # write file |
With statement
1 | with open('sample.txt', 'w') as myFile: |
Read file line by line
1 | f = open("file.txt", "r") |
Reference:
Class
You can assign attributes to an Object. functions defined in an class should have a ‘self’
reference to the instance by convention. It can be named differently but not recommended.
1 | class Animal: |
init method
the init method is init(two underscore characters, followed by init, and then two more underscores)
1 | def __init__(self, sound): |
toString method
str is supposed to return a string representation of an object.
1 | def __str__(self): |
Inheritance
syntax
1 | class BaseClass: |
Sample
1 | class Animal: |
Module
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
A module can contain executable statements as well as function definitions.
calc.py file defines module calc with two functions
1 | def add(num1, num2): |
Import calc module and use its functions
1 | import calc |
Importing build-in Module
1 | # import a math module |
from … import …
import specific functions from a module
1 | from math import ceil, floor |
import functions and datatypes
1 | from collections import namedtuple, deque |
**from … import * **
import all functions in a module, not recommended
1 | from math import * |
Package
A package is a collection of related python modules. A Package must contain a special file __init__.py. The initialization code in __init__.py will be executed when package is imported. You will usually see import statements in __init__.py file.
Install package using pip
Install an individual package globally in a Mac
1 | python3 -m pip install Flask |
If you have multiple packages to install, you can create a requirements.txt file with a list of packages to install.
1 | Flask==1.1.1 |
run the following command to install packages
1 | python3 -m pip install -r requirements.txt |
uninstall package
1 | python3 -m pip uninstall Flask |
Virtual Environment
A virtual environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
Create a virtual environment
1 | virtualenv <folder_name> |
we usually create a virtual environment in the project folder. The virtual environment folder is usually named ‘.venv’
1 | virtualenv venv |
Activate the virtual environment
1 | source venv/bin/activate |
To confirm the virtual environment is activated, check the location of your Python interpreter:
1 | which python |
To install packages in the virtual environment
1 | python3 -m pip install colorama |
now you can import the package in your python script
1 | from colorama import Fore |
To Deactivate the virtual environment
1 | deactivate |
Main method
1 | if __name__ == '__main__': |
The above code snippe is used quite often. It checks if a module is being imported or not.
In other words, the code within the ‘if’ block will be executed only when the code runs directly. Here ‘directly’ means ‘not imported’.