🚀 Python CheatSheet

Here’s the cheat sheet formatted in Markdown code snippets:

First Start

  • print(): Outputs text to the console.
      print("Hi Nasser!")

Operations and Variables

  • Operations:
    • + (addition): 2 + 3 results in 5
    • - (subtraction): 5 - 2 results in 3
    • * (multiplication): 4 * 3 results in 12
    • / (division): 10 / 2 results in 5.0
    • ** (exponentiation): 2 ** 3 results in 8
    • // (floor division): 7 // 2 results in 3
    • % (modulus): 10 % 3 results in 1
  • Variable Assignment: Assigns a value to a variable.
      x = 10
  • Variable Types:
    • int: x = 5
    • float: y = 5.0
    • str: name = "Alice"
    • bool: is_active = True
  • type(): Returns the type of a variable.
      type(x)  # Returns <class 'int'>
  • Comparison Operators:
    • ==: Equal
    • >: Greater than
    • <: Less than
    • >=: Greater than or equal to
    • <=: Less than or equal to
        x == 10  # True

Input and Casting

  • input(): Gets user input.
      name = input("Enter your name: ")
  • Casting: Converts between types.
      num_str = "10"
      num_int = int(num_str)  # Converts to int

Strings

  • lower(): Converts to lowercase.
      "HELLO".lower()  # 'hello'
  • len(): Returns length of string.
      len("Python")  # 6
  • capitalize(): Capitalizes the first letter.
      "hello".capitalize()  # 'Hello'
  • upper(): Converts to uppercase.
      "hello".upper()  # 'HELLO'
  • title(): Capitalizes the first letter of each word.
      "hello world".title()  # 'Hello World'
  • strip(): Removes leading/trailing whitespace.
      "  hello  ".strip()  # 'hello'
  • replace(): Replaces a substring.
      "Hello World".replace("World", "Python")  # 'Hello Python'
  • count(): Counts occurrences of a substring.
      "banana".count("a")  # 3
  • isalpha(): Checks if all characters are alphabetic.
      "Hello".isalpha()  # True
  • isdigit(): Checks if all characters are digits.
      "123".isdigit()  # True
  • isalnum(): Checks if all characters are alphanumeric.
      "Hello123".isalnum()  # True
  • in: Checks if a substring exists in a string.
      "Hello" in "Hello World"  # True
  • Concatenation:
    • Using +:
        "Hello" + " World"  # 'Hello World'
    • Using ,:
        print("Hello", "World")  # 'Hello World'
    • f-string:
        name = "Alice"
      f"Hello, {name}!"  # 'Hello, Alice!'
  • String Slicing: General syntax: string[start:end:step]
      text = "Hello"
      text[1:4]  # 'ell'

Control Flow

  • if/else:
      if x > 10:
          print("Greater")
      else:
          print("Not greater")
  • if/elif/else:
      if x > 10:
          print("Greater")
      elif x == 10:
          print("Equal")
      else:
          print("Less")

Loops

  • for loop:
      for i in range(5):
          print(i)  # 0 to 4
  • while loop:
      count = 0
      while count < 5:
          print(count)
          count += 1  # 0 to 4

Lists

  • Creation:
      my_list = [1, 2, 3]
  • len():
      len(my_list)  # 3
  • Slicing:
      my_list[0:2]  # [1, 2]
  • remove():
      my_list.remove(2)  # [1, 3]
  • pop():
      my_list.pop()  # Removes and returns the last item (3)
  • clear():
      my_list.clear()  # []
  • append():
      my_list.append(4)  # [4]
  • extend():
      my_list.extend([5, 6])  # [4, 5, 6]
  • List Comprehension:
      squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

File I/O

  • open: Opens a file.
      file = open('file.txt', 'r')  # Opens for reading
  • close: Closes a file.
      file.close()
  • open with ‘with’:
      with open('file.txt', 'r') as file:
          content = file.read()
  • read(): Reads the entire file.
      content = file.read()
  • readline(): Reads one line.
      line = file.readline()
  • readlines(): Reads all lines into a list.
      lines = file.readlines()

Dictionaries

  • Create a Dictionary:
      my_dict = {
          "name": "Alice",
          "age": 30,
          "city": "New York"
      }
  • Access a Value in a Dictionary:
      age = my_dict["age"]  # 30
  • pop(key): Removes the specified key and returns its value.
      city = my_dict.pop("city")  # 'New York'
  • items(): Returns a view object containing the key-value pairs.
      items = my_dict.items()  # dict_items([('name', 'Alice'), ('age', 30)])
  • keys(): Returns a view object containing the dictionary’s keys.
      keys = my_dict.keys()  # dict_keys(['name', 'age'])
  • values(): Returns a view object containing the dictionary’s values.
      values = my_dict.values()  # dict_values(['Alice', 30])
  • update(): Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.
      my_dict.update({"age": 31, "country": "USA"})

Functions

  • Create a Function:
      def greet(name):
          return f"Hello, {name}!"
  • Call the Function:
      message = greet("Alice")  # 'Hello, Alice!'
  • Function with No Arguments:
      def say_hello():
          print("Hello, World!")
      
    say_hello()  # Outputs: Hello, World!
  • Function with a Flexible Number of Arguments (*args):
      def add_numbers(*args):
          return sum(args)
    
    result = add_numbers(1, 2, 3, 4)  # 10
  • Function with Keyword Arguments (**kwargs):
      def print_info(**kwargs):
          for key, value in kwargs.items():
              print(f"{key}: {value}")
    
    print_info(name="Alice", age=30)  
    # Outputs:
    # name: Alice
    # age: 30
  • Function with Default Arguments:
      def greet(name="Guest"):
          return f"Hello, {name}!"
    
    message1 = greet("Alice")  # 'Hello, Alice!'
    message2 = greet()          # 'Hello, Guest!'
  • Function Returning Multiple Values:
      def get_user_info():
          return "Alice", 30
    
      name, age = get_user_info()  # name = 'Alice', age = 30
  • Lambda Function: A small anonymous function.
      square = lambda x: x ** 2
      result = square(5)  # 25
  • Function Documentation: Use docstrings to document the function.
      def multiply(x, y):
          """Multiply two numbers and return the result."""
          return x * y
    
      print(multiply.__doc__)  # 'Multiply two numbers and return the result.'
  • Higher-Order Functions: Functions that take other functions as arguments.
      def apply_function(func, value):
          return func(value)
    
      result = apply_function(square, 10)  # 100