Cheet Sheet – Python 🐍

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. πŸ‘‹πŸΌ

SyntaxDescription
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 TypeExample
Integerx = 5
Floaty = 3.14
Stringname = "Alice"
Booleanis_active = True
Listlst = [1, 2, 3]
Tupletup = (1, 2, 3)
Dictionaryd = {"key": "value"}
Sets = {1, 2, 3}

SyntaxDescription
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.

SyntaxDescription
def greet(name):Defines a function.
return f"Hello, {name}!"Returns a value.
lambda x: x * 2Lambda (anonymous) function.

OperationExample
Concatenation"Hello" + " World"
Repetition"Hi" * 3
Slicing"Python"[0:3] β†’ 'Pyt'
Methods"hello".upper() β†’ 'HELLO'
Format Stringsf"My age is {age}"

OperationExample
Access Elementlst[0]
Appendlst.append(4)
Removelst.remove(2)
Slicelst[1:3]
Sortlst.sort()

OperationExample
Access Valued["key"]
Add/Update Keyd["new_key"] = "value"
Keysd.keys()
Valuesd.values()
Itemsd.items()

SyntaxDescription
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.

SyntaxDescription
try:Start a try block.
except Exception as e:Catch an exception.
else:Execute if no exception occurs.
finally:Always execute.

SyntaxDescription
class Person:Define a class.
def __init__(self, name):Constructor.
def greet(self):Instance method.

ModuleExample
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! 🌍

…………

Leave a Reply

Your email address will not be published. Required fields are marked *