Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Cheat Sheet

This document is a comprehensive Python cheat sheet covering topics from basic syntax and data types to advanced concepts like decorators and generators. It includes examples for variables, operators, control flow, functions, data structures, file handling, exception handling, object-oriented programming, and modules. Each section provides concise code snippets to illustrate the concepts effectively.

Uploaded by

cuic70725
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Cheat Sheet

This document is a comprehensive Python cheat sheet covering topics from basic syntax and data types to advanced concepts like decorators and generators. It includes examples for variables, operators, control flow, functions, data structures, file handling, exception handling, object-oriented programming, and modules. Each section provides concise code snippets to illustrate the concepts effectively.

Uploaded by

cuic70725
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python Cheat Sheet (Beginner to Advanced)

1. Basics

# Variables & Data Types


x = 10 # Integer
y = 3.14 # Float
name = "Nitin" # String
is_true = True # Boolean

# Comments
# This is a single-line comment
'''This is a multi-line comment'''

# Type Checking & Conversion


print(type(x)) # <class 'int'>
print(int(y)) # 3
print(float(x)) # 10.0
print(str(x)) # '10'

2. Operators

# Arithmetic
a, b = 10, 3
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.33 (Division)
print(a // b) # 3 (Floor Division)
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponentiation)

3. Control Flow

# If-Else
x = 20
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
# Loops
for i in range(5): # 0 to 4
print(i)

while x > 15:


print(x)
x -= 1

4. Functions

# Function Definition
def greet(name):
return f"Hello, {name}!"

print(greet("Nitin")) # Hello, Nitin!

# Lambda Function
square = lambda x: x ** 2
print(square(5)) # 25

5. Data Structures

# List
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
my_list.append(6) # Add element
my_list.pop() # Remove last element

# Tuple (Immutable)
my_tuple = (1, 2, 3)

# Set (Unique values)


my_set = {1, 2, 3, 3}
print(my_set) # {1, 2, 3}

# Dictionary (Key-Value Pair)


my_dict = {"name": "Nitin", "age": 15}
print(my_dict["name"]) # Nitin

6. File Handling

# Writing to a file
with open("test.txt", "w") as file:
file.write("Hello, world!")
# Reading a file
with open("test.txt", "r") as file:
content = file.read()
print(content)

7. Exception Handling

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")

8. OOP (Object-Oriented Programming)

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
return f"Hi, I'm {self.name}!"

p1 = Person("Nitin", 15)
print(p1.greet()) # Hi, I'm Nitin!

9. Modules & Libraries

import math
print(math.sqrt(25)) # 5.0

import random
print(random.randint(1, 10)) # Random number between 1 and 10

import datetime
print(datetime.datetime.now()) # Current date & time

10. Advanced Concepts

# List Slicing
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # [20, 30, 40]
# Generators
def gen():
yield 1
yield 2
yield 3

g = gen()
print(next(g)) # 1
print(next(g)) # 2

# Decorators
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper

@decorator
def say_hello():
print("Hello!")

say_hello()

You might also like