It is a quick reference for seasoned developer, who already master at least one programming language. for myself, I have worked with C# for more than 10+ years. this reference can help you easily translate from other language to python
Naming Variables : camel Case
myVariable
Data Types:
Text Type:
str "hello world"
Numeric Types:
int : (10),
long :(101L)
float: (10.01),
complex: (3j)
Sequence Types:
list: ["a","b","c","d"],
tuple: immutable
myTuple = ("a","b","c","d")
tuple[0]="New assignment" TypeError: 'tuple' object does not support item assignment
range: generate a sequence of integer
range(5) : 0 1 2 3 4
range(0, 5, 2) : 0 2 4
Mapping Type:
dictionary: list of key value pairs
myDictionary={"key1:value1, "key2:value2 }
Set Types:
set
frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Comments
# single comment
"""
multiple line comments
another line comments
"""
Strings
Multiline and Formatting Strings
Indentation
Arithmetic Operators
Comparison Operators
<, >, <=, >=, ==, !=, <>
Logical Operators
and, or, not
Assignment Operators
a=b assign value from right to left
a +=b a=a+b
a -=b a=a-b
a *=b a=a*b
a /=b a=a/b
a **=b a=a**b
a //=b a=a//b 10 //=3 => 10//3=3
If Statements
if condition:
elif condition:
else:
Ternary If Statements
message= "true condition" if condition else "false condition"
Lists
operators:
Length: len([1, 2, 3] => 3
Concatenation: ["a", "b", "c"] + [1, 2, 3] => ["a", "b", "c", 1, 2, 3]
Repetition: [a, b] * 3 => ["a", "b", "a", "b", "a", "b"]
Slicing [1: ] myList=[1, 2, 3] myList[1:] => [2, 3]
Indexing :
myList=[1, 2, 3]
offsets starting from zero: myList[1] => 2
if negative counting from the right side: myList[-1] => 3
Built in List methods
max(myList) =>3
min(myList) => 1
list: convert iterable object into a list
list("abcd")=>[a, b, c, d]
list(123456) TypeError: 'int' object is not iterable
list("123456") => [1, 2, 3, 4, 5 ,6]
list({12, "ab", [1, 3]}) => [12, "ab", [1, 3]]
Useful List Methods
- append : add item the end of the list
- count: find the number of occurrence of object
- extend: append iterable object to the list
- insert: add item to the offset index
- pop: return the item from the list
- remove: remove item from the list
- reverse: reverse the order of items in the list
- sort: sort items in the list
Deleting Items from Lists
del list(obj) exactly like list.remove(obj)
Sets
not allow to have duplicate item
Set Union Intersection & Difference
union : setA | setB
intersect: setA & setB
differece: setA - setB
symmetric_difference: setA ^ setB
Dictionaries
key value pairs data structure
myDict ={
"key1" : value1,
"key2" : value2,
"key3" : value3
}
value1=myDict["key1"]
Functions:
len:
Methods:
For Loops
for item in list or set:
print(item)
Loop Through Dictionaries
for key in dict:
print(f"key: {key} value: {dict[key]}")
While Loop
number=0
while number < 3
number +=1
Break and Continue
break: exist the the loop if condition meets
number=0
while number < 3
if number==2
break;
number +=1
continue: continue the loop if the condition is true
number=0
while number < 3
if number <=2
continue;
number +=1
Functions
def myfunction():
print("this is my first function")
Built in Functions and Import Statement
import python module:
import math
import specific method from the module
from math import floor
Creating Modules
create a python file myModule.py
in another file use import myModule to reference the moudule
printing all variables and function names of the "myModule" module
dir(myModule)
Classes and Objects
classes are the blueprints of objects
objects are the instances of classes
Creating Classes and Objects
class person
#define the constructor
def __init__(self, firstName,lastName):
self.fistName=firstName
self.lastName=lastName
myObject=person("first name", "last name")
Inheritance
class driver(person) #driver is inherited from person
Printing Objects
# override method
def __str__(self) -> str:
return f"last name: {self.firstName}, last name: {self.lastName}"
Working With Dates
from datetime import datetime #work with datetime
from datetime import date #work with actual date
Formatting Dates
now=datetime.now()
now.strftime("datetime string formatter")
Creating Files
file =open("./myfile.txt", "w") # create a text file myfile.txt in the current working dir
flags: a -> append
r -> read
r+ -> read and write
w -> write
file.close() # to properly close the file being read or write
Reading From Files
file =open("./myfile.txt", "r")
file.read()
file.close()
A Better Way To Work With Files
import os.path
if(os.path.isfile(myfile.txt): #ensure the file exists before read write operations
with open("./myfile.txt", "r") as file
file.read()
Fetching Data From Internet
import json
from urllib import request
response = request.urlopen(("https://fakerapi.it/api/v1/companies?_quantity=5"))
resjson = json.loads(response.read())
print(resjson["data"])
Pip & Modules
pip3: python package manager
pip3 install requests
Request Module
import json
import requests
response = requests.get(("https://fakerapi.it/api/v1/companies?_quantity=5"))
print(response.text)
jsonData = json.loads(response.text)
print(jsonData["data"])
Text To Speech
pip3 install pyttsx3
import pyttsx3
pyttsx3.speak
Asterik *
* is argument-unpacking and ** keyword-argument-unpacking operators
The single star *
unpacks the sequence/collection into positional arguments
The double start ** uses a dictionary and thus named arguments.