Python Cheat Sheet - Essential Quick and Easy Guide
Python Cheat Sheet - Essential Quick and Easy Guide
Cheat Sheet
Essential Quick And Easy Guide
Python Syntax
Basics
For multi-line comments, you can use triple quotes (either single or double).
x = 5
name = "John"
Variable names should be descriptive and follow the naming convention of using
lowercase letters and underscores for spaces.
user_age = 25
favorite_color = "blue"
To find out the data type of any Python object, you can use the type() function. For example:
name = 'jane'
print(type(name))
#Output: 'str'
if condition:
# Code to execute if the condition is true
elif another_condition:
# Code to execute if the another_condition is true
else:
# Code to execute if none of the conditions are true
For loops:
while condition:
# Code to execute while the condition is true
Inside these loops, you can use conditional and control statements to control your
program's flow.
def function_name(parameters):
# Code to execute
return result
function_name(arguments)
Now that we've gone over the Python basics, let's move on to some more advanced
topics.
Create a list:
my_list = [1, 2, 3]
Access elements:
my_list[0]
Access elements:
my_list.append(4)
Create a tuple:
my_tuple = (1, 2, 3)
Access elements:
my_tuple[0] #Output: 1
Create a set:
my_set = {1, 2, 3}
Add an element:
my_set.add(4)
Remove an element:
my_set.remove(1)
Create a dictionary:
Access elements:
my_dict['key1'] #Output:'value1'
my_dict['key3'] = 'value3'
del my_dict['key1']
Remember to practice and explore these data structures in your Python projects to
become more proficient in their usage.
Now that your file is open, you can use different methods to read its content:
file_obj.close()
Alternatively, you can use the with statement, which automatically closes the file after the block
of code completes:
file_obj.close()
file_obj.close()
By following these steps and examples, you can efficiently navigate file operations in
your Python applications. Remember to always close your files after working with them to
avoid potential issues and resource leaks.
try:
quotient = 5 / 0
except ZeroDivisionError as e:
print("Oops! You're trying to divide by zero.")
In this case, the code inside the try block will raise a ZeroDivisionError exception. Since we
have an except block to handle this specific exception, it will catch the error and print the
message to alert you about the issue.
try:
# Your code here
except ZeroDivisionError as e:
# Exception handling
finally:
print("This will run no matter the outcome of the
try and except blocks.")
For instance:
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be a negative value.")
try:
validate_age(-3)
except ValueError as ve:
print(ve)
To use a module's contents in your code, you need to import it first. Here are a few different
ways to import a module:
import <module_name>: This imports the entire module, and you can access its
contents using the syntax 'module_name.content_name.'
for example:
import random
c = random.ranint()
from <module_name> import *: This imports all contents of the module. Be careful
with this method as it can lead to conflicts if different modules have contents with the
same name.
import <package_name.module_name>
Structure your code with modules and packages to make it more organized and
maintainable. This will also make it easier for you and others to navigate and
comprehend your codebase.
class ClassName:
# Class attributes and methods
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
In this example, a new Dog object can be created with a name and breed, and it has a
bark method that prints "Woof!" when called.
To implement inheritance, add the name of the superclass in parentheses after the
subclass name:
class SubclassName(SuperclassName):
# Subclass attributes and methods
class Poodle(Dog):
def show_trick(self):
print("The poodle does a trick.")
A Poodle object would now have all the attributes and methods of the Dog class, as well as
its own show_trick method.
Python employs name mangling to achieve encapsulation for class members by adding a
double underscore prefix to the attribute name, making it seemingly private.
class Example:
def __init__(self):
self.__private_attribute = "I'm private!"
def __private_method(self):
print("You can't see me!")
NumPy's efficient array manipulations make it particularly suitable for projects that require
numerical calculations.
By utilizing Pandas, you can easily import, analyze, and manipulate data in a variety of formats,
such as CSV, Excel, and SQL databases. If you're interested in Pandas, you can check out our
video on How To Resample Time Series Data Using Pandas To Enhance Analysis: Link here
Using Requests, you can quickly and efficiently interact with various web services and APIs.
By using Beautiful Soup in conjunction with Requests, you can create powerful web
scraping applications that gather information from a wide array of websites.
ENTERPRISEDNA.CO