I am sure you can find cheet sheets about python from many sources but I hope that having all the examples and exercises in one place will be useful for you. π
Your feedback is very valuable to me, I am looking forward to hearing it. ππΌ
Basics
Syntax Description print("Hello, World!")Prints output to the console. # CommentSingle-line comment. """ Multi-line """Multi-line comment or docstring. x = 10Variable assignment. type(x)Returns the type of a variable.
Data Types
Data Type Example Integer x = 5Float y = 3.14String name = "Alice"Boolean is_active = TrueList lst = [1, 2, 3]Tuple tup = (1, 2, 3)Dictionary d = {"key": "value"}Set s = {1, 2, 3}
Control Flow
Syntax Description if x > 0:Conditional statement. elif x == 0:Else if condition. else:Executes if none of the above conditions are met. for i in range(5):For loop from 0 to 4. while x < 10:While loop. breakExits the loop. continueSkips to the next iteration.
Functions
Syntax Description def greet(name):Defines a function. return f"Hello, {name}!"Returns a value. lambda x: x * 2Lambda (anonymous) function.
String Operations
Operation Example Concatenation "Hello" + " World"Repetition "Hi" * 3Slicing "Python"[0:3] β 'Pyt'Methods "hello".upper() β 'HELLO'Format Strings f"My age is {age}"
List Operations
Operation Example Access Element lst[0]Append lst.append(4)Remove lst.remove(2)Slice lst[1:3]Sort lst.sort()
Dictionary Operations
Operation Example Access Value d["key"]Add/Update Key d["new_key"] = "value"Keys d.keys()Values d.values()Items d.items()
File Handling
Syntax Description with open("file.txt", "r") as file:Open a file in read mode. content = file.read()Read entire file content. file.write("Hello!")Write to a file.
Exception Handling
Syntax Description try:Start a try block. except Exception as e:Catch an exception. else:Execute if no exception occurs. finally:Always execute.
Classes
Syntax Description class Person:Define a class. def __init__(self, name):Constructor. def greet(self):Instance method.
Common Modules
Module Example import mathImport math module. math.sqrt(16)Square root β 4.0. import randomRandom module. random.randint(1, 10)Random integer between 1 and 10. import datetimeDatetime module. datetime.datetime.now()Current date and time.
…………
Thank you for your time; sharing is caring! π
…………