Saturday 11 February 2023

python quick guide - python tutorial - python cheat sheet


Basic syntax

  • Variables: x = 5, y = "hello"
  • Comments: # This is a comment
  • Printing output: print("hello world")
  • User input: name = input("What is your name? ")
  • If statement:

 if x > 10:

    print("x is greater than 10")

elif x == 10:

    print("x is equal to 10")

else:

    print("x is less than 10")


Loops:

  • For loop:
for i in range(10):

    print(i)


  • While loop:
i = 0
while i < 10:
    print(i)
    i += 1


Data types
  • Numbers: x = 5, y = 3.14, z = 2 + 3j
  • Strings: name = "John"
  • Lists: my_list = [1, 2, 3, "hello"]
  • Tuples: my_tuple = (1, 2, 3)
  • Dictionaries: my_dict = {"name": "John", "age": 30}
  • Sets: my_set = {1, 2, 3}
Functions
  • Defining a function:
def greet(name):
    print("Hello, " + name)

  • Calling a function: greet("John")
  • Return value from a function:
def add(x, y):
    return x + y

result = add(3, 4)
print(result)


Modules
  • Importing a module: import math
  • Using a function from a module: math.sqrt(4)
  • Importing a specific function from a module: from math import sqrt
  • Renaming a module or function: import math as m, from math import sqrt as square_root
File I/O
  • Opening a file: my_file = open("filename.txt", "r")
  • Reading from a file: contents = my_file.read()
  • Writing to a file: my_file.write("Hello, world!")
  • Closing a file: my_file.close()
Error handling
  • Try/except block:
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
  • Raise an exception: raise ValueError("Invalid value")
Object-oriented programming
  • Defining a class:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print("Hello, my name is " + self.name)


  • Creating an object from a class: person = Person("John", 30)
  • Accessing object attributes: print(person.name)
  • Calling object methods: person.greet()

List comprehensions
  • Create a list of squares: squares = [x**2 for x in range(10)]
  • Create a list of even numbers: evens = [x for x in range(10) if x % 2 == 0]
Lambda functions
  • Define a lambda function: square = lambda x: x**2
  • Call a lambda function: result = square(4)
Built-in functions
  • len(): len("hello")
  • max(): max([1, 2, 3])
  • min(): min([1, 2, 3])
  • sum(): sum([1, 2, 3])
  • range(): range(10)
  • zip(): list(zip([1, 2, 3], ["a", "b", "c"]))
File handling
  • Opening a file for reading: file = open("file.txt", "r")
  • Reading the contents of a file: contents = file.read()
  • Closing a file: file.close()
  • Opening a file for writing: file = open("file.txt", "w")
  • Writing to a file: file.write("Hello, world!")
Regular expressions
  • Importing the re module: import re
  • Matching a pattern in a string: match = re.search(pattern, string)
  • Finding all occurrences of a pattern in a string: matches = re.findall(pattern, string)
  • Replacing a pattern with a string: new_string = re.sub(pattern, replacement, string)
JSON handling
  • Importing the json module: import json
  • Converting a dictionary to JSON: json_string = json.dumps(dictionary)
  • Converting JSON to a dictionary: dictionary = json.loads(json_string)
  • Reading JSON from a file: with open("file.json", "r") as file: data = json.load(file)
  • Writing JSON to a file: with open("file.json", "w") as file: json.dump(data, file)
Decorators
  • Defining a decorator function:
def my_decorator(func):
    def wrapper():
        print("Before function is called.")
        func()
        print("After function is called.")
    return wrapper

Using a decorator:

@my_decorator
def my_function():
    print("Function is called.")


Virtual environments
  • Creating a virtual environment: python -m venv myenv
  • Activating a virtual environment:
  • Windows: myenv\Scripts\activate
  • Unix/Linux: source myenv/bin/activate
  • Installing packages in a virtual environment: pip install package_name
  • Deactivating a virtual environment: deactivate
Concurrency
  • Threading:
    • Importing the threading module: import threading
    • Creating a thread: thread = threading.Thread(target=my_function)
    • Starting a thread: thread.start()
    • Waiting for a thread to finish: thread.join()
  • Multiprocessing:
    • Importing the multiprocessing module: import multiprocessing
    • Creating a process: process = multiprocessing.Process(target=my_function)
    • Starting a process: process.start()
    • Waiting for a process to finish: process.join()
Web scraping
  • Importing the requests module: import requests
  • Making a GET request: response = requests.get(url)
  • Parsing HTML with BeautifulSoup:
    • Importing the BeautifulSoup module: from bs4 import BeautifulSoup
    • Creating a BeautifulSoup object: soup = BeautifulSoup(html, "html.parser")
    • Finding elements by tag name: elements = soup.find_all("tag")
    • Finding elements by class name: elements = soup.find_all(class_="class-name")
    • Finding elements by ID: element = soup.find(id="id-name")
Debugging
  • Printing to the console: print(variable)
  • Using a debugger:
    • Importing the pdb module: import pdb
    • Setting a breakpoint: pdb.set_trace()
    • Stepping through code: n (next), s (step into), c (continue), l (list)
Classes and objects
  • Defining a class:
class MyClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def my_method(self):
        print("Hello, world!")
  • Creating an object: my_object = MyClass("value1", "value2")
  • Accessing object attributes: my_object.arg1
  • Calling object methods: my_object.my_method()
Context managers
  • Using a context manager to open a file:
with open("file.txt", "r") as file:
    contents = file.read()
    • Using a custom context manager:
    class MyContextManager:
        def __enter__(self):
            print("Entering context.")
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            print("Exiting context.")

    with MyContextManager() as my_context:
        print("Inside context.")

    Generators
    • Defining a generator function:
    def my_generator():
        yield 1
        yield 2
        yield 3
    • Creating a generator object: my_gen = my_generator()
    • Iterating over a generator: for value in my_gen: print(value)
    Multithreading
    • Importing the threading module: import threading
    • Creating a new thread:
    def my_thread_function():
        print("Hello, world!")

    my_thread = threading.Thread(target=my_thread_function)
    my_thread.start()

    Networking
    • Importing the socket module: import socket
    • Creating a socket:
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    my_socket.bind(("localhost", 12345))
    my_socket.listen()

    • Connecting to a socket:
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    my_socket.connect(("localhost", 12345))

    • Sending and receiving data:
    my_socket.send(b"Hello, server!")
    data = my_socket.recv(1024)



    Labels:

    0 Comments:

    Post a Comment

    Note: only a member of this blog may post a comment.

    << Home