Python Cheatsheet

Basic Syntax

Basic Syntax and Functions for Python Programming

Boilerplate

print("Welcome To Pythongdb")

Input

input_value = input("Enter a value: ")

Data Types

 Character Type

 Typically a single octet (one byte). It is an integer type.

character = 'a'

Integer Type

 The most natural size of an integer for the machine.

integer = 42

Float Type

A single-precision floating-point value.

float_number = 3.14

Double Type

A double-precision floating-point value.

double_number = 3.141592653589793

Void Type

Represents the absence of the type.

void = None

Boolean Type

boolean = True

Escape Sequences

Alarm or Beep

print("\a")

Backspace

print("\b")

Form feed

print("\f")

Newline

print("\n")

Carriage return

print("\r")

Tab

print("\t")

Backslash

print("\\")

Single quote

print("\'")

Double quote

print("\"")

Question mark

print("\?")

Octal Number

print("\nnn")

Hexadecimal Number

print("\xhh")

Null Character

print("\0")

Comments

Single-line comment

# This is a single-line comment

Multi-line comment

"""

This is a

multi-line

comment

"""

Strings

Declaring String

string_variable = "Hello, World!"

Append Function


first_name = "John "

last_name = "Doe"

full_name = first_name + last_name

print(full_name)

Length Function

string_variable = "Pythongdb"
print("The length of the string is:", len(string_variable))

Accessing and Changing String Characters

string_variable = "Hello, World!"

This line will raise an error as strings are immutable

Maths

max Function

print(max(25, 140))

min Function

print(min(55, 50))

sqrt Function

import math
print(math.sqrt(144))

ceil Function

print(math.ceil(1.9))

floor Function

print(math.floor(1.02))

pow Function

print(pow(2, 3))

Decision Making Instructions

If Statement

if condition:
       # Code to execute if condition is True

If-else Statement

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

If-elif-else Statement

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if both condition1 and condition2 are False

Ternary Operator

variable = expressionTrue if condition else expressionFalse

Switch Case Statement

variable = expression
switch variable:
    case value1:
        # Code to execute if variable equals value1
        break
    case value2:
        # Code to execute if variable equals value2
        break
    default:
        # Code to execute if variable doesn't match any case

Iterative Statements

while Loop

while condition:
    # Code to execute while condition is True

do-while Loop

while True:
    # Code to execute
    if condition:
        break

for Loop

for variable in iterable:
    # Code to execute for each element in iterable

Break Statement

break

Continue Statement

continue

References

Creating References

variable1 = "Value1"  # variable1 variable
variable2 = variable1  # reference to variable1

Pointers

Python doesn’t have explicit pointers like C++

Functions and Recursion

Function Definition

def function_name(parameter1, parameter2):
    # Code to be executed
    return result

Function Call

result = function_name(argument1, argument2)

Recursion

def recurse():
    # Code to be executed
    recurse()

Object-Oriented Programming

Class

class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

    def method_name(self, parameter):
        # Code to be executed

Object

object_name = ClassName(argument1, argument2)

Constructors

class ClassName:
    def __init__(self):
        print("Code With Harry")

object_name = ClassName()

Encapsulation

class ExampleEncap:
    def __init__(self):
        self.__num = 0
        self.__ch = ''

    def get_num(self):
        return self.__num

    def get_ch(self):
        return self.__ch

    def set_num(self, num):
        self.__num = num

    def set_ch(self, ch):
        self.__ch = ch

obj = ExampleEncap()
obj.set_num(100)
obj.set_ch('A')
print(obj.get_num())
print(obj.get_ch())

File Handling

Creating and Writing to a Text File

file = open("filename.txt", "w")
file.write("File Handling in Python")
file.close()

Reading the File

file = open("filename.txt", "r")
content = file.read()
print(content)
file.close()

Opening a File

file = open("test.txt", "in")
file = open("test.txt", "out")
file = open("test.txt", "binary")
file = open("test.txt", "app")
file = open("test.txt", "ate")
file = open("test.txt", "trunc")
file = open("test.txt", "nocreate")
file = open("test.txt", "noreplace")

Closing a File

file.close()

Exception Handling

try:
    # Code to try
    raise Exception("An error occurred")  # If a problem arises, throw an exception
except Exception as e:
    # Code to handle errors
    print(e)

Download this cheatsheet