Python Cheat Sheet

Python Cheat Sheet

Aung Kyaw Nyunt
This cheat sheet covers some of the most commonly used Python commands, functions, and syntax to help you work efficiently with Python code.
Use this cheat sheet to jumpstart your Python learning journey.
1. Python Basics
1.1. Print and Input

print() – Output to the console.
print("Hello, world!")
input() – Get user input.
name = input("Enter your name: ") # Takes user input
1.2. Variables and Data Types

String – Text data.
myString = "Hello, Python!"
Integer – Whole number.
myInt = 42
Float – Decimal number.
myFloat = 3.14
Boolean – True or False value.
isActive = True
1.3. Comments

Single-line comment:
# This is a comment
Multi-line comment (using triple quotes):
'''This is a multi-line comment'''
2. Data Structures
2.1. Lists

Create a list:
myList = [1, 2, 3, 4, 5]
Access list items:
print(myList[0]) # Access first element (index 0)
Add an item:
myList.append(6) # Add 6 to the list
Remove an item:
myList.remove(3) # Remove the first occurrence of 3
Slice a list:
subList = myList[1:4] # Get items from index 1 to 3
2.2. Tuples

Create a tuple:
myTuple = (1, 2, 3)
Access tuple items:
print(myTuple[0]) # Access first item
Tuples are immutable – Cannot change values once created.
2.3. Dictionaries

Create a dictionary:
myDict = {"name": "John", "age": 25}
Access dictionary items:
print(myDict["name"]) # Access value for 'name'
Add or update a key-value pair:
myDict["city"] = "New York"
Delete a key-value pair:
del myDict["age"]
2.4. Sets

Create a set:
mySet = {1, 2, 3, 4}
Add an item:
mySet.add(5)
Remove an item:
mySet.remove(3)
3. Conditionals and Loops
3.1. If, Elif, Else

If statements:
if x > 10: print("x is greater than 10")
Elif and Else:
if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10")
3.2. For Loop

Iterate over a range:
for i in range(5): # From 0 to 4 print(i)
Iterate over a list:
myList = ["apple", "banana", "cherry"] for fruit in myList: print(fruit)
3.3. While Loop

While loop example:
count = 0 while count < 5: print(count) count += 1
3.4. Break, Continue, and Pass

break – Exit the loop.
for i in range(5): if i == 3: break print(i)
continue – Skip the current iteration.
for i in range(5): if i == 3: continue print(i)
pass – Do nothing, used as a placeholder.
for i in range(5): if i == 3: pass # Do nothing print(i)
4. Functions
4.1. Define a Function

Basic function definition:
def greet(name): print("Hello, " + name)
Function with return value:
def add(a, b): return a + b
4.2. Lambda Functions

Lambda function (anonymous function):
add = lambda a, b: a + b print(add(2, 3)) # Output: 5
4.3. Default Argument Values

Function with default argument:
def greet(name="Guest"): print("Hello, " + name) greet() # Output: Hello, Guest greet("Alice") # Output: Hello, Alice
5. Exception Handling
5.1. Try, Except

Basic exception handling:
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
Handling multiple exceptions:
try: x = int("abc") except ValueError: print("Invalid input!") except ZeroDivisionError: print("Cannot divide by zero!")
Finally – Code that always runs:
try: file = open("myfile.txt", "r") except FileNotFoundError: print("File not found!") finally: print("This will always execute.")
6. File I/O
6.1. Open, Read, and Write Files

Open a file:
file = open("file.txt", "r") # "r" = read mode
Read contents:
content = file.read() # Read entire file print(content) file.close() # Always close the file when done
Write to a file:
with open("file.txt", "w") as file: # "w" = write mode file.write("Hello, world!")
Reading lines from a file:
with open("file.txt", "r") as file: for line in file: print(line.strip()) # Strip newline characters
7. Classes and Objects
7.1. Define a Class

Creating a class:
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def bark(self): print(self.name + " says Woof!")
Create an object:
myDog = Dog("Rex", "German Shepherd") myDog.bark() # Output: Rex says Woof!
7.2. Inheritance

Inheritance in classes:
class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): print("Dog barks") dog = Dog() dog.speak() # Output: Dog barks 8. Useful Built-in Functions 8.1. len() Get length of a list, string, etc.: myList = [1, 2, 3] print(len(myList)) # Output: 3 8.2. range() Generate a range of numbers: for i in range(5): # Loop from 0 to 4 print(i) 8.3. sorted() Sort a list: myList = [3, 1, 4, 1, 5, 9] print(sorted(myList)) # Output: [1, 1, 3, 4, 5, 9]
8. Useful Built-in Functions
8.1. len()

Get length of a list, string, etc.:
myList = [1, 2, 3] print(len(myList)) # Output: 3
8.2. range()

Generate a range of numbers:
for i in range(5): # Loop from 0 to 4 print(i)
8.3. sorted()

Sort a list:
myList = [3, 1, 4, 1, 5, 9] print(sorted(myList)) # Output: [1, 1, 3, 4, 5, 9]
8.4. sum()

Get the sum of a list:
numbers = [1, 2, 3, 4] print(sum(numbers)) # Output: 10
8.5. min() and max()

Find minimum and maximum values:
numbers = [3, 1, 4, 1, 5, 9] print(min(numbers)) # Output: 1 print(max(numbers)) # Output: 9
This cheat sheet provides the essential Python concepts, syntax, and functions to help you write clean, efficient Python code.
Happy Codding ;)
https://www.applix.info
© All right Reserved. Inspired Codes...
Get In Touch
Rule and Policy