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
2
3
4
5
6
7
8
print("hello python")
print("hello", "python")
print(234.56)

# use **** as separator, separtor can be anything or empty string
print("hello", "python", "3", sep="****") # => hello****python****3
print("hello", "python", "3", sep="") # => hellopython3
print("hello", "python", "3", sep="\n")

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
2
3
4
5
# getting input
inputString = input("please enter a string")

# It is useful to keep window open after script complete execution
input("press close to exit")

To get input as int. Note that you need to use Ctrl+D to send EOF to indicate no more input.

1
2
import sys
a = int(sys.stdin.read())

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
2
3
import math
a=math.inf
b=-math.inf

use type() to get object type

type() is also a build-in function. type() reference

1
2
3
type(123)    # => <class 'int'>
type(123.45) # => <class 'float'>
type("foo") # => <class 'str'>

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
2
3
4
5
6
7
my_var = None
if my_var is None:
print("my_var is empty") # "my_var is empty"

my_var = "123"
if my_var is not None:
print("my_var is not empty") # 'my_var is not empty"

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

str reference

  • 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
s = "Hello World"
s[0] # => H

# slicing
s[0:3] # => Hel

# String concat
"Hello" + " " + "World" # Hello World

# formatting
print("My name is %s and I am %d years old" % ("Mark", 42)) # => My name is Mark and I am 42 years old

# get string length
len(s)

# search for a substring
s.find("Wor")

# upper case
s.upper()

# lower case
s.lower()

# format
"the Sum of 1 + 2 is {0}".format(1+2) # => 'the Sum of 1 + 2 is 3'

# convert number to string
str(1)

# check string contains
if "de" in "abcde":
print("de is found")

Control Statement and Iterator

If Statement

1
2
3
4
5
6
7
8
x = input("x:")
y = input("y:")
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')

While Statement

1
2
3
4
5
count = 0
while count < 10:
print(count)
count += 1

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
2
3
nums = [1, 3, 7, 10]
for i in nums:
print(i) # output 1 3 7 10

range function

for loop with range() function.

1
2
3
4
5
6
7
# output 0 to 4
for i in range(0, 5)
print(i)

# output 10 to 0
for i in range(10, -1, -1):
print(i)

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
2
for i in [1, 2, 3, 4]:
pass

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
2
3
4
5
6
7
8
9
empytList = []    # empty list

people = ["Alice", "Bob"]
print(people[0]) # => Alice
people[1] = "Ted" # => change list item value

people.append("Cathy") # append new element
people.remove("Cathy") # remove element

Use List as Stack

1
2
3
stack = [1, 2, 3]
stack.append(4)
print(stack.pop()) # 4

Queue

Using list as Queue is not efficient. Use collections.deque because it has fast appends and pops at both ends.

1
2
3
4
5
from collections import deque

queue = deque([1, 2, 3])
queue.append(4)
print(queue.popleft()) # 1

Tuple

Tuple - tuple is like an immutable list.

1
2
3
numbers = (2, 4 ,6 ,8)
numbers[0] # print 2
numbers[1:3] # print (4, 6)

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
2
3
4
5
6
7
8
employees = { "alice": "developer", "bob": "sales" }
employees["alice"] # output 'developer'
employees["alice"] = "CEO" # sets value of 'alice' to be 'CEO'
employees.keys() # dict_keys(['alice', 'bob'])
employees.values() # dict_values(['CEO', 'sales'])
del employees["alice"] # delete key "alice"
employees["abc"] # KeyError: 'abc'
employees.get("abc") # None

Function

Functions are defined using ‘def’

1
2
3
4
def add(num1, num2):
return num1 + num2

add(2, 3) # => 5

Python supports multiple return values.

1
2
3
4
def cal(num1, num2):
return num1+num2, num1-num2

x,y = cal(10, 5)

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
2
3
4
5
6
7
8
9
10
11
# write file
myfile = open('output.txt', 'w')
myfile.write("ABC\n")
myfile.write("DEF\n")
myfile.close()

# read file
myfile = open('output.txt', 'r')
content = myfile.read()
print(content)
myfile.close()

With statement
1
2
3
4
5
6
7
with open('sample.txt', 'w') as myFile:
myFile.write("ABC\n")
myFile.write("DEF\n")

with open('sample.txt', 'r') as myFile:
print(myFile.read())

Read file line by line

1
2
3
4
5
6
f = open("file.txt", "r")

for line in f:
print(line.strip())

f.close()

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
2
3
4
5
6
7
class Animal:
def speak(self):
print(self.sound)

animal = Animal()
animal.sound = "..."
animal.speak()

init method

the init method is init(two underscore characters, followed by init, and then two more underscores)

1
2
def __init__(self, sound):
self.sound = sound

toString method

str is supposed to return a string representation of an object.

1
2
def __str__(self):
return 'Animal'

Inheritance

syntax

1
2
3
4
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Sample

1
2
3
4
5
6
7
8
9
10
class Animal:
def speak(self):
print(self.sound)

class Cat(Animal):
def speak(self):
print("meow")

cat = Cat()
cat.speak()

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
2
3
4
5
6
def add(num1, num2):
return num1 + num2

def subtract(num1, num2):
return num1 - num2

Import calc module and use its functions

1
2
3
import calc
print(calc.add(2, 3))
print(calc.subtract(2, 3))

Importing build-in Module

1
2
3
# import a math module
import math
print(math.sqrt(16))

from … import …

import specific functions from a module

1
2
3
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0

import functions and datatypes

1
from collections import namedtuple, deque

**from … import * **

import all functions in a module, not recommended

1
2
from math import *
print(sqrt(16))

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
2
from colorama import Fore
print(Fore.RED + "Hello World")

To Deactivate the virtual environment

1
deactivate

Main method

1
2
if __name__ == '__main__':
print("in main method") # => in main method

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’.

Reference