Python Language Cheat Sheet



Overview

  1. Python Programming Language Cheat Sheet
  2. Python Language Cheat Sheet
  3. Python Basics Cheat Sheet
Interp­reted progra­mming language developed in late 80s inspired by ABC language.

PYTHON CHEAT SHEET Python is a most popular general-purpose, high-level programming language which was created in 1991 by Guido van Rossum and developed by Python Software Foundation to concentrate on the readability of code with its extensive use of white space. Title: Python date: 2020-12-23 18:41:20 icon: icon-python background: bg-blue-600 tags: python categories: Programming intro: The Python cheat sheet is a one-page reference sheet for the Python 3 programming language.

  • Python is a beautiful language. It’s easy to learn and fun, and its syntax is simple yet ele-gant. Python is a popular choice for beginners, yet still powerful enough to back some of the world’s most popular products and applications from companies like NASA, Google, Mozilla, Cisco, Microsoft, and Instagram, among others.
  • The Python ‘re’ module must first be imported: import re w for w in text1 if re.search('^ab',w) – ‘Regular expressions’ is too big of a topic to cover here. Chunking Collocations are good for getting a quick glimpse of what a text is about.
Extens­ibility is one of its major features. Libraries such as Scapy and Requ­ests unlock Python's potential.Basic Python scripts are fast to write and many libraries support easy creation of HTTP requests, parsing of respon­sesMany tools are written in Python.It is widely available and is installed natively on macOS, most Linux distri­but­ions, annd some UNIX systems.Python is easy to installed, and you can check version with python -vPython requires consistent indent­ation, using 2 or 4 spaces is common. Tab should be avoided.

Python 2 versus Python 3

Python 2.x is legacy, Python 3.x is the present and future. The final major release of Python 2.7 was in 2010.Python 2 is still the default version on macOS and Linux, though Python 3 is often included by called 'Python 3'

Python 3 Features

Major improv­ement is better Unicode support, all test strings being Unicode by defaultClean Unicod­e/byte separationException chainingFunction annota­tionsSyntax for keywor­d-only argumentsExtended tuple unpackingNon-local variable delcar­ationsOther changes include print and exec being statements and integers using floor division.

Data Types and Syntax

Stringvar='st­rin­g'Bool­eanvar=TrueInte­gervar=86Floatvar=3.1­4159if/e­lif­/elsecondit­ional execution of functionsinput( )Pythonreturns a string by defaultPython programming cheat sheet pdfint( )changes a string to an integerBoolean operat­orsand, or, not as well as comparison operators ( <, <=, >, >=< )for loopsiterates through a setwhile loopsiterates until a condition met

Lists and Dictio­naries

Lists

Python Programming Language Cheat Sheet

Programming are fundam­ental data structure they contain an ordered list of data.
**list = ['thing1', 'thing2', 'thing3']Dict­ion­aries are similar to lists but they are unordered key: value pairs.
**dictionary = {'key': 'value'}In other languages, dict­ion­aries are known as asso­ciative arrays or hash­es.

Web Libraries

urlliburll­ib2 - It can perform basic authen­tic­ation, it does not handle underlying details like base-64 encoding or author­ization headers. Python 3 splits functi­onality into urllib.re­quest and urllib.errorurll­ib3http­lib - Python 3 renamed this http.cl­ienthttp­lib2Requ­ests developed with a number of PEP 20 idioms in mindPEP= Python Enhanc­ement Propos­als
PEP 20 are 'The Zen of Python­'
Requests follows:
1. Beautiful is better than ugly
2. Explicit is better than implicit
3. Simple is better than complex
4. Complex is better than compli­cated
5. Readab­ility counts.

Requests

Abstracts many lower-­level details.Supports multiple auth­ent­ication methods: Basic, Digest, Kerberos, NTLM, AWS, OAuth1Supports POST with options sent via a dictionary called 'data' in {'vari­able': 'value'}; multiple variables can be passedRequests can also POST data from a file.Handles TLS/­SSL transp­arently verifying x.509 certif­icates by default (verif­y=True) and will exit if it is invalid. To connec tot a site with an invalid certif­icate by setting verify=False.
r=requests.get('https://'invalid.cert', verify=False)
print=(r.text)Example of Post script:Python language reference cheat sheet
#! /usr/b­in/­python3
import requests
r=requ­est­s.p­ost­('h­ttp­://­sec­uri­ty.c­om­/fo­rm_­aut­h/l­ogi­n.php', data={­'user': 'admin', 'pass': 'admin', 'button': 'Login'})
print(­r.text)
  • Python is a multi-paradigm general-purpose, object-oriented programming language
  • It is a cross-platform programming language so code python file written in one system can be run same on different systems.
  • Easy to learn.
  • Simple Syntax and akin to pseudocode.
  • Automatic Garbage Collection.
  • It is an open-source programming language.

Applications of Python

Python is a very versatile language and it is used in many IT fields such as:

  • Web Development (back-end)
  • Desktop Applications
  • Data Science.
  • Machine Learning
  • Artificial Intelligence.

Major Characteristic of Python

  • Very Simple Programming language.
  • Python has the most libraries.
  • Support Object-Oriented programming
  • Ideal Programming language for a beginner.
  • Robust and Secure
  • Highly Scalable
  • Use Interpreter
  • Dynamic Programming language.
  • Multi-threading.

Python IDE’s

There are many IDE’s on the internet for Python the two most recommended ones are:

  • PyCharm (By Jetbrains)
  • Atom (Powered by GitHub)

Standard Data Types in Python:

Python has two types of Data types:

  • Base Type.
  • Container Type.
Base Type
Data type NameData Type SyntaxSize
Integer Numberint14
Floating Point Numbersfloat16
Booleanbool14
stringstr26
bytesb’’21
Container Type Data Types
Data type NameData Type SyntaxExample
List (Ordered)list()[1,2,3] or list(range(1,4))
Tuple (Ordered)tuple()(1,2,3)
Dictionary (Unordered)dict(){0:1, 1:2, 2:3}
Set (unordered)set(){1,2,3}

Python Operators

Python has some standard operators which include arithmetic operators too.

Operator Name OperatorExample
Addition or concatenation+1+2

Or

“hello” + ”world”

Subtraction40 – 10 à 30
Multiplication*40 * 10 à 100

[0]*2 à[0,0]

division/10/5 à 2.0
Floor division//10 // 5 à2
Modules%10 % 5 à 0
Exponential**2**3 à 8

Python Comparison Operator

There are some operators in python which are used to compare two objects or values and return a Boolean value True and False:

Operator Name OperatorExample
Smaller than <2 < 3 èTrue
Greater than>3 > 2 èTrue
Smaller than and equal to<=2 <= 2 èTrue
Greater than and equal to>=3 >= 3 èTrue
Not equal to!=2 != 3èTrue
Equal to comparison2 2 èTrue

Logical Operators

Python has three logical Operators:

  • and
  • or
  • not

Python Identifiers

Identifies are the name given to an object, identifiers can be also known as a variable name. There are some rules associated with an identifier or variable name. Using identifies we can give a name to variables, functions, modules, classes.

Identifiers rule:
  • The first letter of an identifier could be a lowercase or upper case Alphabet or _ (underscore symbol), and it could be followed by any alphabet, digit (0,9) and _.
  • There should be no special symbol in identifier except _.
  • Do not use reserved keywords as an identifier.

Variable Assignment

We use equal to “=” symbol to assign an object to an identifier.

The identifier name should be on the left side and value on the right side of the assignment operator.

Example:

x =20

Python AssignmentAssignment operatorExample
Simple and Single Assignment=x = 20
Assignment to same value=x = y = z =100
Multiple Assignment=x, y, z = 10, 20, 30
Swap values with Assignment operator=x, y = y, x
Unpacking sequence using assigmnet operator=x, *y = [20,10,30,70]
Assignment operator for increment+=x+=20
Assignment operator for Decrement-=x -=20

Python I/O

I/O methodsDescription
print()To print out the output
input()To take input from the user

Example:

By default input() accept value as string.

Type Conversion

Using there are many reserved keywords in python which are used to convert the data type of a variable.

Type Conversion Python SyntaxExample
Float to integer

Numeric string to integer

Boolean to integer

int()int(20.11)

int(“200”)

int(True)

Integer to float

Numeric string to float

Boolean to float

float()float(100)

float(“100”)

float(True)

Integer to string

float to string

Boolean to string

str()str(100)

str(100.00)

str(True)

ASSIC Code to characterchr()chr(64) à @
Character to ASSIC codeord()ord(‘@’) à 64
Convert a container data type and a string to a listlist()list(“Hello”)
Convert a container datatype to a dictdict()dict([(1,2), (2,3)])
Convert a container data type to a setset()set([1,2,3,4,5,5])

Indexing Calling in Python

In python String, List and tuple objects support indexing calling.

Example:

Boolean Logic in Python

In python, we often encounter with Boolean values when we deal with comparison operator conditional statements.

Types of Boolean

In python there are two types of Booleans:

  • True
  • False
Boolean OperatorDescriptionExample
FalseIn python False, 0, empty container data type and None Treat as False value.bool(0) à False

320kbps video converter. bool([]) à False

bool({}) à False

bool(None) à False

TrueAnything except 0, None and empty data type in python considered as True Booleanbool(100) à True

Modules Name and Import

Use Syntax
Import the complete moduleimport module
Import complete modules with its all objectsfrom module import *
Import specific objects or class from a modulesfrom module import name_1, name_2
Import specific module and give a temporary namefrom module import name_1 as nam

Python Math Module

Math is the most important and widely used standard module of python, it provides many methods related to mathematics.

Math Module Example

from math import *

cos()cos(90)

-0.4480736161291701

sin()sin(200)

-0.8732972972139946

pi3.141592653589793
pow()pow(2,3) à 8.0
ceil()ceil(12.1) à13
floor()floor(12.9) à12
round()round(12.131,2) à12.13
abs()abs(-29) à 29

Conditional Statement

Python Conditional statement consists of 3 keywords if, elif and else.

Example:

Loops

There are two loops statements present in python:

  • for loop
  • while loop

Example:

Break

It is a statement used inside the loop statement, and it is used to terminate the loop flow and exist from the loop immediately.

Example:

Continue

Continue is the opposite of break, it is also used in loop statements and directly jump to the next iteration.

Example:

Function

To create a user-defined function in python we use the def keyword and to exit from a function we return a value using the return keyword.

Example:

Python List

A list is a collection of different data types, and it stores all elements in a contagious memory location.

Create a list

To create a list we use square brackets [ ].

Example:

Indexing

List support indexing, with the help of indexing we can access the specific element of the list.

Example:

List Slicing

With list slicing, we can access a sequence of elements present in the list.

Example:

List Unpacking
Loop through a List:
Adding Elements in the list:
Removing Elements from a list
If condition with a list
List Comprehension

lst_2 = [i for i in lst ]

Condition inside list comprehension
Zip function to combine two lists

Python Language Cheat Sheet

Map and Filter on a list
List Operations
OperationsDescriptions
lst.append(val)Add items at the end
lst.extend(seq)Add sequence at the end
lst.insert(indx,val)Add value at a specific index
lst.remove(val)To delete the specific value from a list
lst.pop()To remove the last value from the list
Lst.sort()To sort the list

Python Tuples

Tuples in python similar to a list, the only difference is tuples are immutable.

Create a tuple:
Convert a list into a tuple
Indexing In tuple

Python Arrays

Python does not have inbuilt support for arrays but it has standard libraries to for array data structure. Array is a very useful tool to perform mathematical concepts.

Create an Array:

Python Sets

Python set is similar to the mathematic sets, a python set does not hold duplicates items and we can perform the basic set operation on set data types.

Create a Set:
Basic Set operation
Operations NameOperatorExample:
Union|s1 | s2
Intersection&s1 & s2
Differences1 – s2
Asymmetric Difference^s1 ^ s2

Dictionary

Python Basics Cheat Sheet

Dictionary is a collection of key: value pair and the key could only be an immutable data type.

Create a dictionary:
Convert a list into a dictionary:
Accessing Dictionary Elements

We use the key to access the corresponding value.

Pdf
Looping Through a dictionary:

Generator Comprehension

Like a list comprehension, we have generator comprehension in generator comprehension we use parenthesis () instead of sq. brackets [].

Example:

Exception Handling:

In exception handling we deal with runtime error there are many keywords associated with exception handling:

keyword Description
tryNormal processing block
exceptError processing block
finallyFinal block executes for both tries or except.
raiseTo throw an error with a user-defined message.

Example:

Python Class

Class provides the Object-Oriented programming concepts to python.

Create a class
Create a constructor for a class:

The constructor is the special method of class which executes automatically during the object creation of the class.

Magic Methods of class
Magic methodsDescription
__str__()String representation of the object
__init__()Initialization or Constructor of the class
__add__()To override addition operator
__eq__()To override equal to method
__lt__()To override less than operator
Class Private members:

Conventionally to declare an attribute private we, write it name starting with __ double underscore.

Example:

Inheritance:

An inheritance we can use the methods and property of another class:

Example:

Multiple Inheritance:

Basic Generic Operations on Containers

Operators Description
len(lst)Items count
min(lst)To find the minimum item
max(lst)To find the maximum item
sorted(lst)List sorted copy
enumerate (c)Iterator on (index, item)
zip(lst_1,lst_2)Combine two list
all(c)If all items are True it returns True else false
any(c)True at least one item of c is true else false

People Also Read: