Python basics cheat sheet
Python basics cheat sheet
- Prints a message to the screen. - Defines reusable blocks of code. - Stores an ordered collection of items.
Python
Python Python
def greet(name):
print("Hello, World!") fruits = ["apple", "banana", "cherry"]
return f"Hello, {name}!"
- Performs basic arithmetic operations. - Manages and manipulates text data. - Stores values that can be reused and manipulated.
f-Strings:
If else:
Data types:
- Implements conditional logic. - Formats strings using expressions inside curly braces.
- Defines the type of values.
Python Python
Python if x > 0: name = "Alice"
num = 10 # Integer print("Positive") print(f"Hello, {name}")
text = "Python" # String else:
print("Non-positive")
Plus-equals:
File handling:
Loops:
- Adds a value to a variable and assigns the result to that variable.
- Opens, reads, writes, and closes files. - Repeats a block of code multiple times.
Python
Python Python count = 0
with open('file.txt', 'r') as file: for i in range(5): count += 1
content = file.read() print(i)
Python Built-in Data Types Python Modules
- Text data enclosed in single or double quotes. - Unordered collection of unique elements. - Imports a module to use its functions and attributes.
Lists: Tuple:
- Ordered and mutable sequence of elements. - Ordered and immutable sequence of elements. Shorten module:
Dictionary: Numbers:
- Key-value pairs enclosed in curly braces. - Numeric data types like int, float, and complex.
Python
Booleans:
Casting: from math import *
Python
is_active = True Python
Functions and attributes:
x = int(3.8) # 3
Python
from math import pow, pi
print(pow(2, 3))
print(pi)
Python Strings
- Combines two or more strings. - Takes user input as a string. - Access characters using indexes.
Python Python
substr = "Python"[2:5] # 'tho' join_str = ", ".join(["apple", "banana", "cherry"]) Python
length = len("Python")
Python Python
repeat = "Hi! " * 3 # 'Hi! Hi! Hi! ' ends = "python.org".endswit Python
if "Py" in "Python":
print("Found!")
Formatting: Looping:
Python Python
s = "Hello, {}. Welcome to {}.".format(name, place) for char in "Python":
print(char)
Python Lists Commands Python Loops
- Creates a list with specified elements. - Counts occurrences of an element in a list. - Repeats a block of code for a fixed number of times.
Python Python
sublist = fruits[1:3] # ['banana', 'cherry'] repeat_list = [0] * 5 # [0, 0, 0, 0, 0] Python
for i in range(5):
if i == 3:
break
Omitting index: Sort & reverse:
print(i)
- Omits starting or ending index for slicing. - Sorts and reverses a list.
With zip():
Python Python
sublist_from_start = fruits[:2] # ['apple', 'banana'] fruits.sort() # ['apple', 'banana', 'cherry'] - Iterates over multiple iterables in parallel.
sublist_to_end = fruits[1:] # ['banana', 'cherry'] fruits.reverse() # ['cherry', 'banana', 'apple']
Python
names = ["Alice", "Bob"]
With a stride: Access:
scores = [85, 92]
for name, score in zip(names, scores):
- Extracts elements with step size. - Accesses elements by index.
print(name, score)
Python Python
stride_slicing = fruits[::2] # ['apple first_fruit = fruits[0] # 'apple' While:
- Generates a sequence of numbers. - Defines a function with a specific task. - Returns multiple values from a function.
Python Python
for i in range(5): def introduce(name, age): Python
if i == 3: print(f"Name: {name}, Age: {age}") def greet(name="Guest"):
continue introduce(age=30, name="Alice") print(f"Hello, {name}!")
print(i)
Python Python
Python square = lambda x: x ** 2 def add(a, b):
fruits = ["apple", "banana", "cherry"] print(square(5)) print(a + b)
for i in range(len(fruits)): add(3, 5)
print(fruits[i])
Return:
- Creates custom exception classes. - Defines a blueprint for objects. - Redefines methods in a subclass.
Python
class Dog:
def bark(self):
print("Woof!")