0% found this document useful (0 votes)
28 views6 pages

Python Cheat Sheet-3

Uploaded by

Vishwaraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views6 pages

Python Cheat Sheet-3

Uploaded by

Vishwaraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Cheat Sheet

Basic Data Types and Variables


Command Description Syntax Example

Variable
Assigns values to variables variable_name = value name = "Alice"
Assignment

Integer Whole numbers int_var = number age = 25

float_var =
Float Decimal numbers price = 19.99
number.decimal

String Text data str_var = "text" message = "Hello World"

Boolean True/False values bool_var = True/False is_active = True

List Ordered, mutable collection list_var = [item1, item2] numbers = [1, 2, 3, 4]

Ordered, immutable
Tuple tuple_var = (item1, item2) coordinates = (10, 20)
collection

person = {"name": "John", "age":


Dictionary Key-value pairs dict_var = {key: value}
30}

Set Unordered unique elements set_var = {item1, item2} unique_nums = {1, 2, 3}


 

String Operations
Command Description Syntax Example

Concatenation Joins strings together string1 + string2 "Hello" + " World"

f-strings String formatting f"text {variable}" f"Hello {name}"

Length Gets string length len(string) len("Python") # 6

Upper Converts to uppercase string.upper() "hello".upper() # HELLO

Lower Converts to lowercase string.lower() "HELLO".lower() # hello

Strip Removes whitespace string.strip() " hello ".strip() # hello

Replace Replaces substring string.replace(old, new) "hello".replace("l", "x")

Split Splits string into list string.split(delimiter) "a,b,c".split(",")

Join Joins list into string delimiter.join(list) ",".join(["a", "b", "c"])


 

List Operations
Command Description Syntax Example

Append Adds item to end list.append(item) numbers.append(5)

Insert Inserts item at index list.insert(index, item) numbers.insert(0, 10)

Remove Removes first occurrence list.remove(item) numbers.remove(3)

Pop Removes and returns item list.pop(index) last_item = numbers.pop()

Index Finds item index list.index(item) position = numbers.index(5)

Count Counts occurrences list.count(item) count = numbers.count(1)

Sort Sorts list in place list.sort() numbers.sort()

Reverse Reverses list in place list.reverse() numbers.reverse()

Slice Gets portion of list list[start:end:step] numbers[1:4] # items 1-3


 

Dictionary Operations
Command Description Syntax Example

Get Value Gets value by key dict[key] or dict.get(key) person["name"]

Set Value Sets key-value pair dict[key] = value person["age"] = 31

Keys Gets all keys dict.keys() list(person.keys())

Values Gets all values dict.values() list(person.values())

Items Gets key-value pairs dict.items() list(person.items())

Pop Removes and returns value dict.pop(key) age = person.pop("age")

Update Updates with another dict dict.update(other_dict) person.update({"city": "NY"})


 

Control Flow Statements


Command Description Syntax Example

If
Conditional execution if condition: if age >= 18: print("Adult")
Statement

If-Else Two-way conditional if condition: ... else: if score >= 60: print("Pass") else: print("Fail")

if condition1: ... elif if grade >= 90: print("A") elif grade >= 80:
If-Elif-Else Multi-way conditional
condition2: ... else: print("B") else: print("C")

Iterates over
For Loop for item in sequence: for num in [1, 2, 3]: print(num)
sequence

Repeats while
While Loop while condition: while count < 10: count += 1
condition true

Break Exits loop break for i in range(10): if i == 5: break

Continue Skips to next iteration continue for i in range(10): if i % 2 == 0: continue


 

Functions
Command Description Syntax Example

def def greet(name): return f"Hello


Define Function Creates a function
function_name(parameters): {name}"

Returns result from


Return Value return value def add(a, b): return a + b
function

Default Sets parameter def greet(name="World"): return


def func(param=default):
Parameters defaults f"Hello {name}"

Lambda lambda parameters:


Anonymous function square = lambda x: x ** 2
Function expression

Variable positional
Args def func(*args): def sum_all(*args): return sum(args)
arguments

Variable keyword
Kwargs def func(**kwargs): def print_info(**kwargs): print(kwargs)
arguments
 

File Operations
Command Description Syntax Example

Open File Opens a file open(filename, mode) file = open("data.txt", "r")

Read File Reads entire file file.read() content = file.read()

Read Lines Reads file line by line file.readlines() lines = file.readlines()

Write File Writes to file file.write(text) file.write("Hello World")

Close File Closes file file.close() file.close()

With Statement Context manager for files with open(file) as f: with open("data.txt") as f: content = f.read()
 

Exception Handling
Command Description Syntax Example

Handles try: result = 10/0 except ZeroDivisionError:


Try-Except try: ... except ExceptionType:
exceptions print("Cannot divide by zero")

Try-Except- Runs if no try: result = 10/2 except: print("Error") else:


try: ... except: ... else:
Else exception print("Success")

Try-Finally Always executes try: ... finally: try: file = open("data.txt") finally: file.close()

Raise Manually raises raise


raise ValueError("Invalid input")
Exception exception ExceptionType("message")
 

List Comprehensions and Generators


Command Description Syntax Example

Creates list from


List Comprehension [expression for item in iterable] squares = [x**2 for x in range(5)]
expression

Conditional List List comp with [expr for item in iterable if evens = [x for x in range(10) if x
Comp condition condition] % 2 == 0]

Dict {key_expr: value_expr for item square_dict = {x: x**2 for x in


Creates dictionary
Comprehension in iterable} range(5)}

Generator squares_gen = (x**2 for x in


Creates generator (expression for item in iterable)
Expression range(5))
 

Built-in Functions
Command Description Syntax Example

Print Outputs to console print(value1, value2, ...) print("Hello", "World")

Input Gets user input input(prompt) name = input("Enter name: ")

Len Returns length len(object) len([1, 2, 3]) # 3

Range Creates sequence of numbers range(start, stop, step) list(range(1, 10, 2))

Sum Sums numeric values sum(iterable) sum([1, 2, 3, 4]) # 10

Min/Max Finds minimum/maximum min(iterable) / max(iterable) min([5, 2, 8]) # 2

Sorted Returns sorted list sorted(iterable) sorted([3, 1, 4]) # [1, 3, 4]

Zip Combines iterables zip(iter1, iter2, ...) list(zip([1, 2], ['a', 'b']))

Enumerate Adds counter to iterable enumerate(iterable) list(enumerate(['a', 'b']))

Map Applies function to items map(function, iterable) list(map(str.upper, ['a', 'b']))

Filter Filters items by condition filter(function, iterable) list(filter(lambda x: x > 0, [-1, 0, 1]))
 

Classes and Objects


Command Description Syntax Example

Class Definition Defines a class class ClassName: class Person: pass

Constructor Initializes object def init(self, params): def init(self, name): self.name = name

Instance def method(self, def greet(self): return f"Hello,


Method that uses self
Method params): {self.name}"

Variable shared by all class Person: species = "Homo


Class Variable class_var = value
instances sapiens"

Instance
Variable unique to instance self.var = value self.name = name
Variable

Inheritance Inherits from parent class class Child(Parent): class Student(Person): pass

Super Calls parent class method super().method() super().init(name)


 
Modules and Packages
Command Description Syntax Example

Import Module Imports entire module import module_name import math

Import Specific Imports specific items from module import item from math import pi

Import with Alias Imports with different name import module as alias import numpy as np

Import All Imports everything (not recommended) from module import * from math import *
 

Common Built-in Modules


Module Description Common Functions Example

math Mathematical functions sqrt(), sin(), cos(), pi import math; math.sqrt(16)

Random number random(), randint(),


random import random; random.randint(1, 10)
generation choice()

datetime.now(), from datetime import datetime;


datetime Date and time operations
date.today() datetime.now()

os Operating system interface listdir(), getcwd(), mkdir() import os; os.getcwd()

json JSON data handling loads(), dumps() import json; json.loads('{"key": "value"}')

re Regular expressions search(), match(), findall() import re; re.findall(r'\d+', 'abc123def')


 

Operators
Type Operators Description Example

Arithmetic +, -, *, /, //, %, ** Mathematical operations 10 + 5, 10 ** 2

Comparison ==, !=, <, >, <=, >= Compare values 5 == 5, 10 > 5

Logical and, or, not Boolean operations True and False, not True

Assignment =, +=, -=, *=, /= Assign and modify x = 5, x += 3

Membership in, not in Check membership 'a' in 'cat', 5 not in [1,2,3]

Identity is, is not Check identity x is None, x is not None


 

Advanced Features
Command Description Syntax Example

Modifies function
Decorator @decorator_name @staticmethod def func():
behavior

with
Context Manager Resource management with open('file.txt') as f:
context_manager:

@property def name(self): return


Property Getter/setter methods @property
self._name

Multiple Assigns multiple


a, b, c = values x, y, z = 1, 2, 3
Assignment variables

Unpacking Unpacks sequences *args, **kwargs def func(*args): print(args)

Assignment in
Walrus Operator (var := expression) if (n := len(data)) > 10:
expressions
 

You might also like