0% found this document useful (0 votes)
6 views4 pages

Extended Python Cheatsheet Guide

Uploaded by

hello.motto0022
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)
6 views4 pages

Extended Python Cheatsheet Guide

Uploaded by

hello.motto0022
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 Cheatsheet (Extended)

Basics

# Variable assignment
x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
flag = True # Boolean

Type Conversion

int("5") # Converts string to int 5


float("3.14") # Converts string to float 3.14
str(123) # Converts int to string "123"
bool(0) # False, non-zero is True

Control Flow

if x > 0:
pass
elif x == 0:
pass
else:
pass

for i in range(5): # 0 to 4
print(i)

while condition:
break # Exit loop
continue # Skip to next iteration

Lists

fruits = ["apple", "banana", "cherry"]


[Link]("orange")
[Link](1, "mango")
[Link]()
[Link]("banana")
[Link]()
sorted(fruits)
[Link]()
[Link]()
len(fruits)

Dictionaries
person = {"name": "Bob", "age": 30}
[Link]()
[Link]()
[Link]()
[Link]("name")
[Link]({"age": 31})
[Link]("name")

Sets

s = {1, 2, 3}
[Link](4)
[Link]([5, 6])
[Link](2)
[Link](10)
[Link]({4, 5})
[Link]({2, 3})

Tuples

t = (1, 2, 3)
len(t)
[Link](2)
[Link](3)

Built-in Functions

abs(-5)
round(3.1415, 2)
max([1, 2, 3])
min([1, 2, 3])
sum([1, 2, 3])
sorted([3, 1, 2])
list(range(5))
enumerate(['a', 'b'])
zip([1,2], ['a','b'])

String Methods

text = " Hello World! "


[Link]()
[Link]()
[Link]()
[Link]("Hello", "Hi")
[Link]()
"-".join(["a", "b"])
[Link](" H")
[Link]("!")
len(text)

Exception Handling

try:
x = 1 / 0
except ZeroDivisionError as e:
print("Error:", e)
else:
print("No error!")
finally:
print("Always runs")

Functions

def greet(name="World"):
return f"Hello, {name}"

square = lambda x: x * x

Classes & OOP

class Dog:
def __init__(self, name):
[Link] = name

def bark(self):
print(f"{[Link]} says Woof!")

d = Dog("Buddy")
[Link]()

List Comprehensions

squares = [x**2 for x in range(10)]


evens = [x for x in range(10) if x % 2 == 0]

File Handling

with open("[Link]", "w") as f:


[Link]("Hello\n")

with open("[Link]", "r") as f:


print([Link]())

with open("[Link]", "a") as f:


[Link]("World\n")
Useful Modules

import math
[Link](16)
[Link]

import random
[Link](1, 10)

from datetime import datetime


[Link]()

import os
[Link]()
[Link]()

You might also like