Python cheat sheet, Python syntax reference, Python programming examples, Python basics tutorial, Python functions and loops, Python data structures guide, Python file handling, Python OOP, Python shortcuts
Python cheat sheet, Python syntax reference, Python programming examples, Python basics tutorial, Python functions and loops, Python data structures guide, Python file handling, Python OOP, Python shortcuts

Python Cheat Sheet — Complete Syntax Reference and Programming Examples

This Python Cheat Sheet is your quick reference guide for writing efficient Python code. Whether you’re preparing for coding interviews, building web apps, or automating tasks, this page helps you recall syntax, functions, and examples instantly.


Introduction to Python Programming

Python is a high-level, interpreted language famous for its simplicity, readability, and versatility. It supports multiple paradigms like object-oriented, functional, and procedural programming.

Example: Basic Hello World Program

print("Hello, World!")

Output:

Hello, World!

Python Syntax and Variables

Python uses indentation (4 spaces) instead of braces {} for code blocks.

name = "Alice"
age = 25
height = 5.6
is_student = True

print(name, age, height, is_student)

Python Data Types and Type Conversion

Data TypeExampleDescription
intx = 10Integer numbers
floatx = 10.5Decimal numbers
strx = "Python"Text data
boolx = TrueBoolean
listx = [1, 2, 3]Ordered, mutable sequence
tuplex = (1, 2, 3)Ordered, immutable sequence
setx = {1, 2, 3}Unordered, unique elements
dictx = {"name": "Alice", "age": 25}Key-value pairs

Type Conversion Example:

x = "123"
y = int(x)
print(y + 10)

Python Operators Reference Table

Operator TypeExampleDescription
Arithmetic+ - * / % ** //Add, subtract, multiply, divide, modulus, exponent, floor division
Comparison== != > < >= <=Compare two values
Logicaland, or, notBoolean operations
Assignment= += -= *= /=Assign and update values
Membershipin, not inCheck presence in sequences
Identityis, is notCompare object identity
Bitwise`&^ ~ << >>`

Python Conditional Statements

age = 20

if age >= 18:
    print("Adult")
elif age > 13:
    print("Teenager")
else:
    print("Child")

Python Loops and Iteration

For Loop Example

for i in range(5):
    print("Number:", i)

While Loop Example

count = 0
while count < 3:
    print("Count:", count)
    count += 1

Loop Control Statements

  • break → exits loop
  • continue → skips iteration
  • pass → does nothing (placeholder)

Python Functions and Scope

def greet(name="User"):
    """Simple greeting function"""
    return f"Hello, {name}!"

print(greet("Alice"))

Lambda Functions

square = lambda x: x * x
print(square(4))

Python Lists, Tuples, and Dictionaries — Data Structures Quick Reference

Lists

fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
print(fruits[1])  # banana

Tuples

colors = ("red", "green", "blue")
print(colors[0])

Dictionaries

student = {"name": "John", "age": 20, "marks": 88}
print(student["name"])

Python String Handling and Formatting

text = "Python Cheat Sheet"
print(text.lower())
print(text.upper())
print(text.replace("Python", "Awesome Python"))
print(f"{text} is easy to learn!")

Python File Handling Examples

# Write to a file
with open("data.txt", "w") as f:
    f.write("Learning Python is fun!")

# Read a file
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

Python Exception Handling

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("Invalid input!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Done.")

Python Classes and Object-Oriented Programming

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def drive(self):
        print(f"{self.brand} is driving...")

car1 = Car("Tesla", "Red")
car1.drive()

Python Modules and Imports

import math
print(math.sqrt(16))

Custom module:

# mymodule.py
def add(a, b):
    return a + b

# main.py
from mymodule import add
print(add(5, 7))

Python List Comprehension and Generator Expressions

squares = [x * x for x in range(1, 6)]
print(squares)
even_numbers = (x for x in range(10) if x % 2 == 0)
for num in even_numbers:
    print(num)

Python Useful Built-in Functions

FunctionDescription
len()Returns length
type()Returns type
range()Generates sequence
sorted()Returns sorted list
sum()Adds numbers
max(), min()Find extremes
enumerate()Returns index and value
zip()Combines iterables
map(), filter()Apply functions to data

Python Packages and Virtual Environments

pip install requests
pip list

To create a virtual environment:

python -m venv myenv
source myenv/bin/activate  # (Linux/Mac)
myenv\Scripts\activate     # (Windows)

Python File and Directory Operations

import os

os.mkdir("demo_folder")
os.rename("demo_folder", "new_folder")
print(os.getcwd())

Python Regular Expressions (re module)

import re
text = "Contact: hello@phponline.in"
result = re.search(r"\w+@\w+\.\w+", text)
print(result.group())

Python Cheat Sheet Summary Table

TopicKey SyntaxExample
Printprint()print("Hello")
Inputinput()name = input("Enter name:")
Loopfor i in range(n)for i in range(3): print(i)
Functiondef name():def add(a,b): return a+b
List Comprehension[x*x for x in range(5)][1,4,9,16,25]
Try-Excepttry: ... except:try: x=1/0 except: print("Error")
Classclass Name:class Car: pass
Python cheat sheet, Python syntax reference, Python programming examples, Python basics tutorial, Python functions and loops, Python data structures guide, Python file handling, Python OOP, Python shortcuts

Related Internal Resources


Frequently Asked Questions (FAQ)

Q1. Is Python beginner-friendly?
Yes. Python is ideal for beginners because of its clean syntax and readability.

Q2. How can I run a Python program?
Save the file as program.py and run python program.py in the terminal.

Q3. What’s the difference between list and tuple?
Lists are mutable (can be changed); tuples are immutable (fixed).

Q4. What is PEP8?
PEP8 is the official Python style guide. It defines code formatting standards.

Q5. How do I comment in Python?
Use # for single-line comments and triple quotes ('''...''') for multi-line.


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments