Getting Started
Fundamental concepts and basic syntax to begin programming in Python.
Introduction
Links to Linux & Git for learning and reference.
Hello World
A simple program to print "Hello, World!" to the console,
demonstrating basic output.
print("Hello, World!")
The famous "Hello World" program in Python
Variables
Named storage for data, dynamically typed, assigned with a value at
creation.
age = 18 # age is of type int name = "Dinesh" # name is now of type str print(name)
Python can't declare a variable without assignment.
Data Types
Built-in types for storing different kinds of data in Python.
str |
Text |
int, float, complex |
Numeric |
list, tuple, range |
Sequence |
dict |
Mapping |
set, frozenset |
Set |
bool |
Boolean |
bytes, bytearray, memoryview |
Binary |
Slicing String
Extracting a substring using index ranges, supporting negative
indices and steps.
msg = "Hello, World!" print(msg[2:5])
Lists
Ordered, mutable collections of items, supporting various operations
like appending.
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
If Else
Conditional statements to execute code based on whether a condition
is true or false.
num = 200
if num > 0:
print("num is greater than 0")
else:
print("num is not greater than 0")
Loops
Iterate over sequences or repeat code until a condition is met.
for item in range(6):
if item == 3: break
print(item)
else:
print("Finally finished!")
Functions
Reusable blocks of code that perform a specific task, accepting
inputs and returning outputs.
def my_function():
print("Hello from a function")
my_function()
File Handling
Operations to read from and write to files, managing file content
efficiently.
with open("myfile.txt", "r", encoding='utf8') as file:
for line in file:
print(line)
Arithmetic
Basic mathematical operations like addition, subtraction,
multiplication, and division.
result = 10 + 30 # => 40 result = 40 - 10 # => 30 result = 50 * 5 # => 250 result = 16 / 4 # => 4.0 (Float Division) result = 16 // 4 # => 4 (Integer Division) result = 25 % 2 # => 1 result = 5 ** 3 # => 125
Plus-Equals
Shorthand for incrementing a variable or concatenating strings.
counter = 0 counter += 10 # => 10 counter = 0 counter = counter + 10 # => 10 message = "Part 1." message += "Part 2."
f-Strings
Formatted string literals for embedding expressions inside strings
(Python 3.6+).
website = 'cheatsheets.zip'
f"Hello, {website}"
num = 10
f'{num} + 10 = {num + 10}'
Built-in Data Types
Core data structures in Python for storing and manipulating different types
of data.
Strings
Sequences of characters, enclosed in single, double, or triple
quotes for text data.
hello = "Hello World" hello = 'Hello World' multi_string = """Multiline Strings Lorem ipsum dolor sit amet, consectetur adipiscing elit """
Numbers
Numeric types including integers, floating-point numbers, and
complex numbers.
x = 1 # int y = 2.8 # float z = 1j # complex print(type(x))
Booleans
Logical values representing True or False, used in conditional
statements.
my_bool = True my_bool = False bool(0) # => False bool(1) # => True
Lists
Ordered, mutable collections that can store mixed data types.
list1 = ["apple", "banana", "cherry"] list2 = [True, False, False] list3 = [1, 5, 7, 9, 3] list4 = list((1, 5, 7, 9, 3))
Tuple
Ordered, immutable collections, often used for fixed data sequences.
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
tupla = (1, 2, 3, 'python')
print(tupla[0]) # Output: 1
print(tupla.count(1)) # Count occurrences
print(tupla.index(2)) # Find index
tupla1 = (1, 2, 3)
tupla2 = ('a', 'b')
print(len(tupla1)) # Output: 3
print(2 in tupla1) # Output: True
print(tupla1 + tupla2) # Output: (1, 2, 3, 'a', 'b')
print(tupla1[1:]) # Output: (2, 3)
a, b, c, d = tupla # unpacking
Set
Unordered collections of unique items, useful for eliminating
duplicates.
set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))
Dictionary
Key-value pair collections for mapping unique keys to values.
empty_dict = {}
a = {"one": 1, "two": 2, "three": 3}
a["one"]
a.keys()
a.values()
a.update({"four": 4})
a['four']
Casting
Converting data from one type to another, such as int to float or
string.
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Strings
Techniques for manipulating and formatting text data in Python.
Array-like
Accessing individual characters in a string using index positions.
hello = "Hello, World" print(hello[1]) print(hello[-1])
Looping
Iterating over each character in a string using a loop.
for char in "foo":
print(char)
Slicing String
Extracting parts of a string using start, end, and step indices.
s = 'mybacon' print(s[2:5]) print(s[0:2]) print(s[:2]) print(s[2:]) print(s[:2] + s[2:]) print(s[:]) print(s[-5:-1]) print(s[2:6]) s = '12345' * 5 print(s[::5]) print(s[4::5]) print(s[::-5]) print(s[::-1])
String Length
Counting the number of characters in a string using len().
hello = "Hello, World!" print(len(hello))
Multiple Copies
Repeating a string multiple times using the multiplication operator.
s = '===+' n = 8 print(s * n)
Check String
Checking if a substring exists within a string using in/not in.
s = 'spam' print(s in 'I saw spamalot!') print(s not in 'I saw The Holy Grail!')
Concatenates
Combining strings using the + operator or implicit concatenation.
s = 'spam'
t = 'egg'
print(s + t)
print('spam' 'egg')
Formatting
Inserting values into strings using % operator or format() method.
name = "Dinesh Chowdary"
print("Hello, %s!" % name)
print("%s is %d years old." % (name, 23))
txt1 = "My name is {fname}, I'm {age}".format(fname="Dines Chowdary", age=36)
txt2 = "My name is {0}, I'm {1}".format("Dinesh Chowdary", 36)
txt3 = "My name is {}, I'm {}".format("Dinesh Chowdary", 36)
Input
Capturing user input from the console as a string.
name = input("Enter your name: ")
print(name)
Join
Combining a list of strings into a single string with a separator.
"#".join(["Dinesh Chowdary", "Peter", "Vicky"])
Endswith
Checking if a string ends with a specified suffix.
"Hello, world!".endswith("!")
F-Strings (Since Python 3.6+)
Advanced string formatting using f-strings for concise and readable
expressions.
f-Strings Usage
Embedding variables and expressions directly within string literals.
website = 'cheatsheets.zip'
f"Hello, {website}"
num = 10
f'{num} + 10 = {num + 10}'
f"""He said {"I'm Dinesh Chowdary"}"""
f'5 {"{stars}"}'
f'{{5}} {"stars"}'
name = 'Eric'
age = 27
f"""Hello!
I'm {name}.
I'm {age}."""
f-Strings Fill Align
Aligning and padding strings within f-strings using format
specifiers.
f'{"text":10}'
f'{"test":*>10}'
f'{"test":*<10}'
f'{"test":*^10}'
f'{12345:0>10}'
f-Strings Type
Formatting numbers in different bases or notations within f-strings.
f'{10:b}'
f'{10:o}'
f'{200:x}'
f'{200:X}'
f'{345600000000:e}'
f'{65:c}'
f'{10:#b}'
f'{10:#o}'
f'{10:#x}'
F-Strings Others
Additional formatting options like precision, grouping, and
percentages.
f'{-12345:0=10}'
f'{12345:010}'
f'{-12345:010}'
import math
f'{math.pi:.2f}'
f'{1000000:,.2f}'
f'{1000000:_.2f}'
f'{0.25:0%}'
f'{0.25:.0%}'
F-Strings Sign
Specifying signs for numbers in f-strings, including positive and
negative.
f'{12345:+}'
f'{-12345:+}'
f'{-12345:+10}'
f'{-12345:+010}'
Lists
Techniques for creating, manipulating, and iterating over lists.
Defining
Creating lists using literals, constructors, or range functions.
li1 = [] li2 = [4, 5, 6] li3 = list((1, 2, 3)) li4 = list(range(1, 11))
Generate
Creating lists using comprehensions or filtering functions.
list(filter(lambda x : x % 2 == 1, range(1, 20))) [x ** 2 for x in range (1, 11) if x % 2 == 1] [x for x in [3, 4, 5, 6, 7] if x > 5] list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
Append
Adding elements to the end of a list using append().
li = [] li.append(1) li.append(2) li.append(4) li.append(3)
List Slicing
Extracting sublists using start, end, and step indices.
a_list[start:end] a_list[start:end:step] a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] a[2:5] a[-5:-2] a[1:4] a[:4] a[0:4] a[2:] a[2:len(a)] a[:] a[0:6:2] a[1:6:2] a[6:0:-2] a[::-1]
Remove
Removing elements from a list using pop() or del.
li = ['bread', 'butter', 'milk'] li.pop() del li[0]
Access
Retrieving elements from a list using index positions.
li = ['a', 'b', 'c', 'd'] li[0] li[-1] li[4]
Concatenating
Combining lists using extend() or the + operator.
odd = [1, 3, 5] odd.extend([9, 11, 13]) odd = [1, 3, 5] odd + [9, 11, 13]
Sort & Reverse
Sorting lists in ascending order or reversing their order.
li = [3, 1, 3, 2, 5] li.sort() li.reverse()
Count
Counting occurrences of an element in a list.
li = [3, 1, 3, 2, 5] li.count(3)
Repeating
Creating a list with repeated elements using the * operator.
li = ["re"] * 3
Flow Control
Mechanisms to control the execution flow of a program based on conditions.
Basic
Using if, elif, and else for conditional execution.
num = 5
if num > 10:
print("num is totally bigger than 10.")
elif num < 10:
print("num is smaller than 10.")
else:
print("num is indeed 10.")
One Line (Ternary)
Concise conditional expression for assigning values based on a
condition.
a = 330 b = 200 r = "a" if a > b else "b" print(r)
else if
Multiple conditions checked sequentially using elif clauses.
value = True
if not value:
print("Value is False")
elif value is None:
print("Value is None")
else:
print("Value is True")
match case
Pattern matching for selecting code blocks based on value (Python
3.10+).
x = 1
match x:
case 0:
print("zero")
case 1:
print("one")
case _:
print("multiple")
Loops
Iterative constructs for repeating code over sequences or conditions.
Basic
Iterating over a sequence using a for loop.
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
With Index
Using enumerate() to access both index and value during iteration.
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
print(i, value)
While
Repeating code while a condition remains true.
x = 0
while x < 4:
print(x)
x += 1
Break
Exiting a loop prematurely when a condition is met.
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
Continue
Skipping the current iteration and continuing with the next.
for index in range(3, 8):
x = index * 10
if index == 5:
continue
print(x)
Range
Generating a sequence of numbers for iteration using range().
for i in range(4):
print(i)
for i in range(4, 8):
print(i)
for i in range(4, 10, 2):
print(i)
With zip()
Iterating over multiple sequences in parallel using zip().
words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w))
for/else
Executing code when a for loop completes without breaking.
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print("%d is bigger than 100" %n)
break
else:
print("Not found!")
Over Dictionary
Iterating over dictionary keys and values using items().
dineshdict = {
"firstname": "Dinesh",
"lastname": "Challa",
"age": 30
}
x = dineshdict.items()
print(x)
for key, value in dineshdict.items():
print(f"{key} : : {value}")
Comprehensions
Concise syntax for creating lists or dictionaries from iterables.
Comprehension List
Creating lists using a single line with filtering conditions.
languages = ["html", "go", "rust", "javascript", "python"]
newlist = [x for x in languages if "l" not in x]
print(newlist)
oldlist = []
for x in languages:
if "l" not in x:
oldlist.append(x)
print(oldlist)
Comprehension Dictionary
Creating dictionaries using a single line with key-value mappings.
languages = ["html", "go", "rust", "javascript", "python"]
language_dict = {lang: ('l' not in lang) for lang in languages}
print(language_dict)
language_dict2 = {}
for e in languages:
if "l" not in e:
language_dict2[e] = True
else:
language_dict2[e] = False
print(language_dict2)
Functions
Reusable code blocks for performing specific tasks with inputs and outputs.
Basic
Defining a simple function to execute a task.
def hello_world():
print('Hello, World!')
Return
Returning a value from a function for further use.
def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y
add(5, 6)
Positional Arguments
Accepting variable numbers of arguments as a tuple using *args.
def varargs(*args):
return args
varargs(1, 2, 3)
Keyword Arguments
Accepting variable keyword arguments as a dictionary using **kwargs.
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness")
Returning Multiple
Returning multiple values as a tuple from a function.
def swap(x, y):
return y, x
x = 1
y = 2
x, y = swap(x, y)
Default Value
Setting default parameter values for optional arguments.
def add(x, y=10):
return x + y
add(5)
add(5, 20)
Anonymous Functions
Defining short, nameless functions using lambda for one-off use.
(lambda x: x > 2)(3) (lambda x, y: x ** 2 + y ** 2)(2, 1)
@decorator
Modifying function behavior using decorators without altering their
code.
def handle_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return print(f"Error : {e}")
return wrapper
@handle_errors
def divide(a, b):
return a / b
divide(10, 0)
Modules
Reusable libraries or files containing Python code for import and use.
Import Modules
Bringing an entire module into the current namespace.
import math print(math.sqrt(16))
From a Module
Importing specific functions or objects from a module.
from math import ceil, floor print(ceil(3.7)) print(floor(3.7))
Import All
Importing all names from a module into the current namespace.
from math import *
Shorten Module
Assigning a shorter alias to a module for convenience.
import math as m math.sqrt(16) == m.sqrt(16)
Functions and Attributes
Listing all available functions and attributes in a module using
dir().
import math dir(math)
File Handling
Operations for reading, writing, and managing files in Python.
Read File
Reading file contents line by line using a context manager.
with open("myfile.txt") as file:
for line in file:
print(line)
With Line Number
Reading a file while tracking line numbers using enumerate().
file = open('myfile.txt', 'r')
for i, line in enumerate(file, start=1):
print("Number %s: %s" % (i, line))
Write a String
Writing string data to a file using write().
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
file.write(str(contents))
Read a String
Reading the entire content of a file as a string.
with open('myfile1.txt', "r+") as file:
contents = file.read()
print(contents)
Write an Object
Writing a Python object to a file as JSON using json.dumps().
contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents))
Read an Object
Reading a JSON file back into a Python object using json.load().
with open('myfile2.txt', "r+") as file:
contents = json.load(file)
print(contents)
Delete a File
Removing a file from the filesystem using os.remove().
import os
os.remove("myfile.txt")
Check and Delete
Checking if a file exists before deleting it to avoid errors.
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")
Delete Folder
Removing an empty directory using os.rmdir().
import os
os.rmdir("myfolder")
Classes & Inheritance
Object-oriented programming constructs for defining custom data types and
behaviors.
Defining
Creating a class to define a new object type.
class MyNewClass:
pass
my = MyNewClass()
Constructors
Initializing class instances with __init__ method.
class Animal:
def __init__(self, voice):
self.voice = voice
cat = Animal('Meow')
print(cat.voice)
dog = Animal('Woof')
print(dog.voice)
Method
Defining functions within a class to describe object behavior.
class Dog:
def bark(self):
print("Ham-Ham")
charlie = Dog()
charlie.bark()
Class Variables
Variables shared across all instances of a class.
class MyClass:
class_variable = "A class variable!"
print(MyClass.class_variable)
x = MyClass()
print(x.class_variable)
Super() Function
Calling methods from a parent class in a derived class.
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
super().print_test()
child_instance = ChildClass()
child_instance.print_test()
repr() Method
Defining a string representation of an object for printing.
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
dinesh = Employee('Dinesh')
print(dinesh)
User-defined Exceptions
Creating custom exception classes for specific error handling.
class CustomError(Exception):
pass
Polymorphism
Different classes implementing the same method with different
behaviors.
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self()
obj_B.print_self()
Overriding
Redefining a parent class method in a child class.
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self()
Inheritance
Creating a class that inherits attributes and methods from another
class.
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name)
print(Yoki.legs)
Yoki.sound()
@staticmethod
Defining methods that don't require instance access, callable on the
class.
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
print(MyClass.greet("Alice"))
obj = MyClass()
print(obj.greet("Bob"))
Type Hints (Since Python 3.5)
Annotations for specifying variable and function types to improve code
clarity.
Variable & Parameter
Annotating variables and function parameters with expected types.
string: str = "ha"
times: int = 3
result: str = 1 + 2
print(result)
def say(name: str, start: str = "Hi"):
return start + ", " + name
print(say("Python"))
Built-in Data Type
Using typing module to specify complex data types like dictionaries
and tuples.
from typing import Dict, Tuple, List
bill: Dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
"pineapple": 6.53,
}
completed: Tuple[str] = ("DONE",)
succeeded: Tuple[int, str] = (1, "SUCCESS")
statuses: Tuple[str, ...] = (
"DONE", "SUCCESS", "FAILED", "ERROR",
)
codes: List[int] = (0, 1, -1, -2)
Built-in Data Type (3.10+)
Simplified type annotations for built-in types (Python 3.10+).
bill: dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
"pineapple": 6.53,
}
completed: tuple[str] = ("DONE",)
succeeded: tuple[int, str] = (1, "SUCCESS")
statuses: tuple[str, ...] = (
"DONE", "SUCCESS", "FAILED", "ERROR",
)
codes: list[int] = (0, 1, -1, -2)
Positional Argument
Specifying types for variable positional arguments using *args.
def calc_summary(*args: int):
return sum(args)
print(calc_summary(3, 1, 4))
Returned
Annotating the return type of a function.
def say_hello(name) -> str:
return "Hello, " + name
var = "Python"
print(say_hello(var))
Union Returned
Specifying multiple possible return types using Union.
from typing import Union
def resp200(meaningful) -> Union[int, str]:
return "OK" if meaningful else 200
Keyword Argument
Specifying types for variable keyword arguments using **kwargs.
def calc_summary(**kwargs: int):
return sum(kwargs.values())
print(calc_summary(a=1, b=2))
Multiple Returns
Annotating functions that return multiple values as a tuple.
def resp200() -> (int, str):
return 200, "OK"