Basics
- Comments:
Python
# This is a single-line comment """ This is a multi-line comment """
- Variables:
Python
x = 5 name = "Alice" is_valid = True
- Dynamically typed (you don't need to declare the type).
- Case-sensitive (
myVar
is different frommyvar
).
- Data Types:
- Numeric:
int
(integer),float
(floating-point),complex
(complex numbers) - Sequence:
str
(string),list
,tuple
,range
- Mapping:
dict
(dictionary) - Set:
set
,frozenset
- Boolean:
bool
(True
,False
) NoneType
:None
- Numeric:
- Operators:
- Arithmetic:
+
(add),-
(subtract),*
(multiply),/
(divide),//
(floor division),%
(modulo),**
(exponent) - Comparison:
==
(equal),!=
(not equal),>
(greater than),<
(less than),>=
(greater than or equal to),<=
(less than or equal to) - Logical:
and
,or
,not
- Assignment:
=
,+=
,-=
,*=
,/=
,//=
,%=
,**=
- Identity:
is
,is not
(check if objects are the same in memory) - Membership:
in
,not in
(check if a value is present in a sequence)
- Arithmetic:
Control Flow
- Conditional Statements:
Python
if condition: # code to execute if condition is True elif another_condition: # code to execute if another_condition is True else: # code to execute if none of the above conditions are True
- Loops:
for
loop: Iterates over a sequence (list, tuple, string, range, etc.)Pythonfor item in sequence: # code to execute for each item
range(start, stop, step)
: Generates a sequence of numbers.enumerate(sequence)
: Returns pairs of (index, item).
while
loop: Executes as long as a condition is True.Pythonwhile condition: # code to execute while condition is True
- Loop Control Statements:
break
: Exits the loop immediately.continue
: Skips the current iteration and proceeds to the next.pass
: Does nothing (placeholder).
Data Structures
- Lists: Ordered, mutable sequences of items.
Python
my_list = [1, "hello", 3.14] my_list.append(4) # Add to the end my_list.insert(1, "world") # Insert at a specific index my_list.remove("hello") # Remove the first occurrence of a value popped_item = my_list.pop(2) # Remove and return item at index (default: last) length = len(my_list) sliced_list = my_list[1:3] # Slicing (start:end:step)
- Tuples: Ordered, immutable sequences of items.
Python
my_tuple = (1, "hello", 3.14) # Tuples are often used for fixed collections
- Dictionaries: Unordered collections of key-value pairs.
Python
my_dict = {"name": "Bob", "age": 30} print(my_dict["name"]) # Access value by key my_dict["city"] = "New York" # Add a new key-value pair del my_dict["age"] # Delete a key-value pair keys = my_dict.keys() values = my_dict.values() items = my_dict.items() # Returns a list of (key, value) tuples
- Sets: Unordered collections of unique elements.
Python
my_set = {1, 2, 3, 3, 4} # {1, 2, 3, 4} (duplicates are automatically removed) my_set.add(5) my_set.remove(3) union_set = my_set.union({5, 6}) intersection_set = my_set.intersection({2, 4})
Functions
- Defining Functions:
Python
def greet(name="Guest"): # Default argument print(f"Hello, {name}!") return "Greeting sent" # Optional return value message = greet("Charlie") greet() # Uses the default argument
- Function Arguments:
- Positional arguments: Passed in the order they are defined.
- Keyword arguments: Passed with the parameter name (
greet(name="David")
). *args
: Collects extra positional arguments into a tuple.**kwargs
: Collects extra keyword arguments into a dictionary.
- Lambda Functions (Anonymous Functions):
Python
square = lambda x: x**2 result = square(5) # result is 25
Modules and Packages
- Importing Modules:
Python
import math print(math.sqrt(16)) import random as rnd # Alias the module print(rnd.randint(1, 10)) from datetime import date # Import specific names today = date.today()
- Packages: Hierarchical directory structure that organizes modules. Use dot notation to access modules within packages (e.g.,
my_package.my_module
).
Input and Output
print()
: Displays output to the console.Pythonprint("Hello, world!") print("Value:", x, "Another value:", name) # Multiple arguments print(f"Formatted string: {x=}, {name=}") # f-strings (formatted string literals)
input()
: Reads input from the user (returns a string).Pythonuser_input = input("Enter something: ") number = int(input("Enter a number: ")) # Convert to integer
- File Handling:
Python
# Reading from a file with open("my_file.txt", "r") as file: content = file.read() # Read the entire file lines = file.readlines() # Read all lines into a list for line in file: # Iterate over lines print(line.strip()) # Remove leading/trailing whitespace # Writing to a file with open("output.txt", "w") as file: # 'w' for write (overwrites), 'a' for append file.write("Hello, file!\n") file.writelines(["Line 1\n", "Line 2\n"])
Object-Oriented Programming (OOP)
- Classes: Blueprints for creating objects.
Python
class Dog: def __init__(self, name, breed): # Constructor self.name = name self.breed = breed def bark(self): print("Woof!") my_dog = Dog("Buddy", "Golden Retriever") print(my_dog.name) my_dog.bark()
- Objects (Instances): Created from classes.
- Methods: Functions defined within a class.
- Attributes: Variables associated with an object.
- Inheritance: Allows a class to inherit properties and methods from a parent class.
- Polymorphism: Ability of different objects to respond to the same method in their own way.
Error Handling
try...except
Blocks:Pythontry: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (TypeError, ValueError) as e: # Catch multiple exceptions print(f"Another error: {e}") else: print("No error occurred.") # Executed if no exception finally: print("This will always be executed.") # Cleanup code
List Comprehensions
- A concise way to create lists.
Python
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] even_numbers = [x for x in range(20) if x % 2 == 0]
Generator Expressions
- Similar to list comprehensions but create iterators (more memory-efficient for large sequences).
Python
squares_generator = (x**2 for x in range(10)) for num in squares_generator: print(num)
String Formatting
- f-strings (Formatted String Literals): (Python 3.6+) Preferred method.
Python
name = "Eve" age = 25 print(f"My name is {name} and I am {age} years old.") print(f"{2 + 2 = }") # Inline expressions
.format()
method:Pythonprint("My name is {} and I am {} years old.".format(name, age)) print("My name is {0} and I am {1} years old. Again, {0}.".format(name, age)) print("My name is {n} and I am {a} years old.".format(n=name, a=age))
- Old
%
formatting: (Less common in modern Python)Pythonprint("My name is %s and I am %d years old." % (name, age))
Common Built-in Functions
len()
: Returns the length of a sequence.type()
: Returns the type of an object.int()
,float()
,str()
,bool()
,list()
,tuple()
,dict()
,set()
: Type conversion functions.sum()
: Sum of elements in an iterable.min()
,max()
: Minimum and maximum of elements.sorted()
: Returns a new sorted list from the items in an iterable.abs()
: Absolute value.round()
: Rounds a number.pow(base, exp)
: Equivalent tobase ** exp
.zip()
: Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.map(function, iterable)
: Appliesa function to all items of an iterable. filter(function, iterable)
: Filters elements of an iterable based on a function.
This cheatsheet covers many fundamental aspects of Python. As you continue learning and working with Python, you'll encounter more advanced concepts and libraries. Keep practicing and referring to documentation as needed!
Comments
Post a Comment