Python
Python

Python

Others

Projects
Projects
Tasks
Tasks
Gym
Gym
Problem Solving
Problem Solving

0. Introduction

notion image
  • We use programming language to communicate with a computer. It is a High-Level Language
  • The Python Interpreter converts the Python scripts in Byte Code that then the Python VM runs it
  • We need to have Python installed on our system to use it
  • Created by Guido Van Rossum in 1991 inspired by the Monty Python’s Flying Circus British Comedy Show
  • The python REPL can be run using the terminal which can be opened by typing python in terminal window
    • notion image
  • To run a python file: python filename.py

1. Variables & Data Types

  • A variable is a container that is stored in the memory
  • A variable is also called as an identifier a = 10 here a is an identifier
  • Numbers: int , float, complex
  • str, bool, None
Naming Conventions:
  1. Can’t start with a number and contain any special characters other than _
  1. Names must be snake_case
# Store multiple Values a, b, c, = 1, 2, 3 # Other Naming Conventions # camelCase # PascalCase # kebab-case # snake_case # mumblecase
Operators:
  1. Arithmetic Operators: +, -, *, /
  1. Assignment Operator: =, +=, -=, etc.
  1. Comparison Operators: ==, >, , , etc. (Always a bool)
  1. Logical: and, or, not

Types

  • The type() function gives us the type
  • Type casting means converting from one type to another. int(), float(), str(), bool(), list()
  • The input() function helps to take input but as a str

2. Strings

  • Sequence of characters enclosed in quotes. Single, Double of Triple Quotes (multiline)
  • Strings are immutable
  • Strings have index position starting from 0. The length len() still is natural number
  • Python also supports negative indices (backwards)
  • All string methods gives us a new string they don’t mutate the original
  • Comments: either # or """ """ for multiline (3 quotes start/end)
# Multiline Strings print(""" Multiple Lines We can print """) print("Hello", end="") # Will not go in new line # String Slicing name = "Phleebs" print(name[start:end:step]) # Inclusive, Exclusive name.index(el) # Gives index or error name.find(el) # Index of -1 if not found 'a' in name # bool name.replace(with, what) # Returns new str # Create duplicate new_name = name[:] new_name[:5] # From starting new_name[2:] # From 2 all the way upto end new_name[::2] # Every second new_name[::-1] # Reversed String # Concatenation print("First" + "Second") #FirstSecond # F Strings print(f"The sum of 2 and 2 is {2 + 2}") # Interpolation # Format String print("This is something {}".format("Hello")) # Old

Methods

string = "Phleebs fugers rovity" len(str) string.index(el) # Index or error string.find(el) # Index or -1 string.replace(with, what) string.startswith("Ph") # True string.endswith('yo') # False string.upper() string.lower() string.capitalize() string.title() # Phleebs Fugers Rovity string.count('a') # 0 string.strip() # Removes whitespace from both ends

Escape Sequence Characters

  • For newline \n, \t, \b, \” (skips)

3. Lists & Tuples

Lists

  • List is an ordered container to store values of any data type
  • Lists are mutable
fruits = ["🍎", "🍌", "🍊", "🥝", "🍍"] fruits.append("Chai") # Ends at end fruits.insert(index, element) fruits.extend(iterable) # Takes an iterable fruits.pop() # Removes from end fruits.pop(index) # Removes at index fruits.remove(element) # Takes value fruits.reverse() # Mutates original fruits.count(el) # Count occurences # Pokemon List fruits = ["🍎", "🍌", "🍊", "🥝", "🍍"] print('-'.join(fruits)) # 🍎-🍌-🍊-🥝-🍍 # List Unpacking a, b, *c = pokemon (🍎, 🍌, [...])

Comprehension: TODO

  • [expression for item in iterable]
  • [expression for item in iterable if condition]
notion image

Matrix

  • 2D or multi-dimensional list
  • Used in image processing
matrix = [ [1, 0, 1], [0, 2, 0], [1, 0, 1] ] # Take out the 2 from the matrix print(matrix[1][1]) # 2

Tuples

  • Immutable lists
  • Very few methods but very fast and optimal
  • Used when we need a collection that is not going to mutate
my_friends = ("Cat", "Kowel", "Dino", "Puppy", "Rabbit") a = (1,) # Tuples with only one element # Methods my_fruits.count("Cat") # 1 my_fruits.index(el) # Concatenation new_tuple = first_tuple + second_tuple # Membership "Cat" in my_fruits # True # Unpacking a, b, *c = my_fruits print(a, b, c) # "Cat" , "Kowel", [rest]

4. Dictionary & Set

  • Dictionary are key value pairs
  • They are also called as Objects in JS
  • The data we get from an API is in JSON format which is similar to a dict
  • It is unordered (now ordered), mutable and indexed, can’t contain duplicate keys
friends_loan = { "Alok": 100, "Shubham": 20, "Rohan": 10, "Sir": 60 } # Methods friends_loan.keys() friends_loan.values() friends_loan.items() # list of tuples # Updates otherwise adds them friends_loan.update({"Alok": 120, "Smith": 10}) # Will give error friends_loan["Ajay"] # None, if we use bracket # notation we get an error friends_loan.get("Ajay") # friends_loan.pop('Sir', none) del friends_loan["Sir"]

Deep vs Shallow Copy

student_copy = student.copy() # shallow copy
notion image

Sets

notion image
  • Is a collection of non-repetitive element
  • It is unordered, unindexed
  • A set can’t contain immutable like a list or a dict
notion image
 
first = {1, 2, 3, 4, 5, "Yo"} second = {"Yo", 5, 7, 8, 9} first.add(el) # Add item first.remove(el) # Removes element first.discard(el) # safe remove first.pop() # Removes any random 😹 first.intersection(second) # "Yo", 5 first.union(second) # All first.clear() # Empties the set first.difference(second) # Only unique ones first.issubset, first.issuperset first.isdisjoing(second) # True when they are complete distinct # Creating an empty set our_set = set()

5. Conditional Expression

  • Also called as control flow allows us to make decisions in our code
  • They are used to guide logical flow of our program
if condition: pass # null operation elif condition: pass else: pass

Operators

# Relational Operators == >= <= # Logical Operators and # both needs to be True or # any one needs to be True not # flips the value

Truthy & Falsey

  • Some values are false and others are true
  • We can check them using the bool() function
  • None, False, 0, 0.0, 0j and empty list, tuple, dict are false

Ternary Operator

  • It is a short hand of a simple if else block
  • This is an expression meaning that we can use inside a formatted string
age = 18 license = 'Approve' if age >= 18 else "Reject"

6. Loops

  • Used to iterate or repeat something
  • There are two types of loops: while and for

While

  • While is when we don’t know prior how many iterations to perform: while True:
  • While loops are the most common to create an infinite loop to occur
  • Write a program to print numbers from 1 to 100 using a while loop
  • Use a while loop to print all the elements of a list
  • We can also append an else clause with loops
# Else will run after the final iteration i = 1 while i <= 10: print("Working") i += 1 else: print("Done")

For

  • We can use it for a pre-defined loop: for i in range(20) 20 times loop
  • To iterate over a list or any iterable for i in iterable
  • We can also add an else clause with a for that will run when the loop will end
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number) else: print("The execution has completed!")
  • The break, continue and pass keyword. The break keyword will break the loop execution, the continue will skip and pass is used as an empty body placeholder. The pass keyword instructs to do nothing

Using Enums

  • They are helpful when we need both the index and the element
for i, char in enumerate("Chai"): print(i, char) # 0 C # 1 h # 2 a # 3 i

7. Functions

  • Block of code that can be reused. It helps in achieving DRY code
  • A function is like a machine that takes in some input (arguments) and outputs (returns) something
  • We define a function and then use it (invoke or call)
  • The code after the return keyword doesn’t run
  • There are two types of functions: built-in functions (like print(), type()) and user defined custom functions using the def keyword
  • Pure functions don’t create side effects meaning that they don’t mutate variables present in their outside scope
def greet(name = "User"): print(f"Hello {name}")

Default Parameters & Keyword Arguments

  • The default way of taking and receiving input is called positional parameters
  • Docstring is a mechanism to write what the function does
# Giving Default Parems def sayHi(name="User"): print(f"Hello {name}") # Passing Arguments as Keywords def greet(first, second): print(f"It's nice to meet you {first} {second}") greet(second='Rishabh', first='Dora') # Keyword Arguments # Docstring def kill(): """ This function kills people who doesn't listen to Sidhu Moose Wala """ print("Listen to Sidhu Moose Wala") help(kill) # Will show up the docstring

Recursion

  • Meaning a function that keeps on calling itself
  • There are several times when we need to solve a problem using recursion
  • It is a famous technique of solving a branch of computer and mathematical problems
  • Improper use can also cause an issue of infinite loop
  • Solve the factorial problem using recursion
  • Task: Create a function to find sum of first n natural numbers using recursion
# Solving Factorial Problem Using Recursion def find_factorial(n): if (n == 0) or (n == 1): return 1 return n * find_factorial(n-1) x = find_factorial(5) print(x)

Scope

  • Scope defines visibility of elements
  • The default scope is called the Global Scope
# An impure function as it modifies a global variable x = 100 def first(): global x # Will reference the outside scope x = 200 print(x) first() print(x)

*args N Positional Arguments

  • With the help of *args we can take any number of positional arguments inside a function
  • Define a function that takes any number of inputs of numbers and returns the maximum
    • def find_max(*nums): max = None for n in nums: if max == None or max < n: max = n return max x = find_max(1, 2000, 3, 4) print(x)

8. Modules, Comments & PIP

  • A module is a file containing code written by somebody else. We can use pip to install modules. For example: requests, flask, django and to install: pip install flask
  • We either have built in modules (os) or external modules
  • Some common packages are: os, requests, dotenv
  • The Python Package Index includes all the packages we can use such as requests, etc.
# Print the contents of the directory import os directory_path = "/" contents = os.listdir(directory_path) print(contents)

9. File Operations