Skip to content

Instantly share code, notes, and snippets.

@iamgauravbisht
Created February 28, 2024 15:45
Show Gist options
  • Save iamgauravbisht/58104d1d8cd8b3004e9a6147d54481bc to your computer and use it in GitHub Desktop.
Save iamgauravbisht/58104d1d8cd8b3004e9a6147d54481bc to your computer and use it in GitHub Desktop.
To Revise Syntax of Python Fast
# print("hello to world from gaurav");
# input will always be a string you have to typeCast to turn them into your desired data type
# x=int(input("Enter a number \t"));
# print (x);
# print(type(x));
# if else
# if x>18:
# print("you are an adult")
# elif x>15:
# print("you are a teenager")
# else :
# print("you are still a child")
# matchCase statement or switchCase statement
# a=input("enter a fruit name \t")
# # syntax of switch statement
# match a:
# case "apple":
# print("your fruit is apple which is red in color")
# case "banana":
# print("your fruit is banana which is yellow in color")
# case "kiwi":
# print("your fruit is kiwi and it is of brown color")
# case _: # this is default case
# print("This is default case which means i don't understand the fruit name you entered")
# loops
# for loops
# for i in "abhishek":
# if i=="a":
# print("this is a")
# else :
# print(i);
# range
# for i in range(10):
# print(i)
# for i in range(2,10):
# print(i)
# for i in range(1,10,2):
# print(i)
# while loop
# x=int(input("enter a number : "))
# while x>4:
# print(x)
# print("i am inside loop")
# x=x-1;
# print("i exited the loop")
# while else
# count = int(input("enter a number : "))
# while (count<9):
# print(count)
# count+=1
# else:
# print("in the else part of while")
# print("outside of while else")
# do while loop is not a method in python
# functions in python
# def gaurav():
# print("hey, i am gaurav");
# gaurav();
# def sum(a,b):
# print("sum : ",a+b);
# sum(1,2)
# pass keyword help you pass the function without writing its body otherwise empty function gives error
# def passLogic(a,b):
# pass
# defaut argument for function
# def sum(a=1,b=2):
# print("sum : ",a+b);
# sum();
# sum(5,4)
# you can also give argument like this
# sum(b=10,a=6)
# Sometimes we may need to pass more arguments than those defined in the actual function. This can be done using variable- length arguments.
# There are two ways to achieve this:
# Arbitrary Arguments:
# While creating a function, pass a * before the parameter name while defining the function. The function accesses the arguments by processing them in the form of tuple.
# Example:
# def name(*name):
# print(type(name))
# print("Hello,", name[0], name[1], name[2]);
# name("James", "Buchanan", "Barnes");
# output : <class 'tuple'> Hello, James Buchanan Barnes
# if i use ** before he parameter name while defining the function. The function accesses the arguments by processing them in the form of dictionary.
# def name(**name):
# print(type(name))
# print("Hello,", name["fname"], name["mname"], name["Iname"])
# name(mname="Buchanan", Iname ="Barnes", fname= "James")
# output : <class 'dict'>
# Hello, James Buchanan Barnes
# List ( known as array in other languges )
# marks=[1,2,3,4,5,"gaurav",True];
# print(marks);
# indexing
# print(marks[2]);
# print(marks[-3]);
# print(marks[len(marks)-3]);
# if "gaurav" in marks:
# print("yes it is present")
# else:
# print("nope it's not present in here");
# if "rav" in "gaurav":
# print("yes");
# print(marks);
# slicing
# print(marks[:]);
# print(marks[1:-1]); #print(marks[1:len(marks)-1])
# slicing with jump index
# print(marks[0:len(marks):2]);
# print(marks[0::2]);
# print(marks[0::3]);
# list comprehension
# list0=[i for i in range(10)];
# print(list0)
# list1=[i*i for i in range(10)];
# print(list1)
# list3=[i*i for i in range(10) if i%2==0];
# print(list3)
# List methods
l = [1, 243, 12, 6, 56, 12, 3]
# l.pop() # this will pop out your last item from the list
# print(l)
# l.append(47); # add the value at the end of list
# print(l);
# l.sort(); # this will sort the list in ascending order
# print(l);
# l.sort(reverse=True) # this will sort the list in descending order
# print(l)
# l.reverse(); # it reverses the original list
# print(l)
# print(l.index(12)); # it finds the number passed value in list and return its index where it first occurs
# print(l.count(12)) #it help count no. of occurance of value in list
# m=l # never do this it copy list by refference so if m changes l also changes
# m=l.copy(); # use this method to copy the list
# m[0]=0
# print(m)
# print(l)
# l.insert(1,999) # inserting value 999 at index 1 and remove the previous value of index 1
# print(l)
# x=[23,8,34,123,412,3,324]
# l.extend(x); # this will add elements of x at the end of list l means : concatenation of l and x
# print(l)
# m=[23,8,34,123,412,3,324]
# k= l + m; # concatenating l and x in k
# print(k);
# Tuples ( a type o list)
# it's immutable means you can't change it
# tup = (1, 5, 6)
# tup[0]=45 # this will give error
# print(type(tup), " : ", tup)
# Tuples methods
# tup = (2, 2, 2, 35, 32, 234, 9)
# r = tup.count(2) # counts how many times a value is present in a tuple
# print(r)
# r = ("gaurav", "saurav", "mahender") + tup # concatenating two tuples
# print(r)
# index(valueToFind,StartIndex,EndIndex)
# r = tup.index(2) # give index of value where it first occured in tuple
# print(r)
# r = len(tup) # length of tuple
# print(r)
# most of the methods are not applicable on tuples because its immutable
# so to operate over tuples you have to convert tuple into list
# tup = (2, 35, 32, 234, 9)
# print(type(tup))
# listOfTuple = list(tup)
# print(type(listOfTuple))
# now you can apply all list methods
# F-string : this is used to format strings
# letter = "{}, I am {} "
# greeting = "Helo"
# name = "Gaurav"
# a = letter.format(greeting, name)
# print(a)
# you can also miss the args order like this letter.format(name, greeting) which will give you wrong output
# to solve that
# we use f-string
# print(f"{greeting}, I am {name}")
# x = 49.9923
# print(f"{x: .2f}") # to show it to 2 decimal points
# print(f"{2*90}")
# print(type(f""))
# print(f"{{greeting}}, I am {{name}}")
# DocStrings
# the comment inside function will be considered
# the docstrings is only viable if its written right after the function defination if there is something before it it wont be consideredas docstings
# def square(n):
# """Takes in a number n, returns the square of n"""
# print(n**2)
# square(5)
# print(square.__doc__) # this will print the comment inside the docstrings
# Recursion
# def factorial(n):
# if n == 0 or n == 1:
# return 1
# else:
# return n * factorial(n - 1)
# print("factorial:", factorial(5))
# Sets : they are unordered and unique
# s = {1, 1, 2, 2, 2, 4, 4, 4, 242, 6, 7, "gaurav", True}
# print(s)
# g = {}
# print(type(g)) # dictionary type
# # to write set we have to write like this
# b = set()
# print(type(b)) # set type
# set Methods
# s = {0, 1, 2, 3, 4, 5, 3}
# g = {4, 5, 6, 7, 8, 9, 0}
# print("union of s and g", s.union(g))
# print(s, g)
# print("updated s : ", s.update(g)) # to update the s and union it with g
# print(s, g)
# intersection and intersection_update():
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
# cities3 = cities.intersection(cities2)
# print(cities3)
# intersection_update()
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
# cities.intersection_update(cities2)
# print(cities)
# symmetric_difference and symmetric_difference_update():
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
# cities3 = cities.symmetric_difference(cities2)
# print(cities3)
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
# cities.symmetric_difference_update(cities2)
# print(cities)
# difference() and difference_update():
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Seoul", "Kabul", "Delhi"}
# cities3 = cities.difference(cities2)
# print(cities3)
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Seoul", "Kabul", "Delhi"}
# print(cities.difference(cities2))
# isdisjoint():The isdisjoint() method checks if items of given set are present in another set. This method returns False if items are present, else it returns True.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
# print(cities.isdisjoint(cities2))
# issuperset():The issuperset() method checks if all the items of a particular set are present in the original set. It returns True if all the items are present, else it returns False.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Seoul", "Kabul"}
# print(cities.issuperset(cities2))
# cities3 = {"Seoul", "Madrid", "Kabul"}
# print(cities.issuperset(cities3))
# issubset():The issubset() method checks if all the items of the original set are present in the particular set. It returns True if all the items are present, else it returns False.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Delhi", "Madrid"}
# print(cities2.issubset(cities))
# add() : If you want to add a single item to the set use the add() method.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities.add("Helsinki")
# print(cities)
# update() : If you want to add more than one item, simply create another set or any other iterable object(list, tuple, dictionary), and use the update() method to add it into the existing set.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities2 = {"Helsinki", "Warsaw", "Seoul"}
# cities.update(cities2)
# print(cities)
# remove()/discard() : We can use remove() and discard() methods to remove items form list.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities.remove("Tokyo")
# print(cities)
# The main difference between remove and discard is that, if we try to delete an item which is not present in set, then remove() raises an error, whereas discard() does not raise any error.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities.remove("Seoul")
# print(cities)
# pop() : This method removes the last item of the set but the catch is that we don’t know which item gets popped as sets are unordered. However, you can access the popped item if you assign the pop() method to a variable.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# item = cities.pop()
# print(cities)
# print(item)
# del : del is not a method, rather it is a keyword which deletes the set entirely.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# del cities
# print(cities)
# clear() : This method clears all items in the set and prints an empty set.
# cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
# cities.clear()
# print(cities)
# Check if item exists : You can also check if an item exists in the set or not.
# info = {"Carla", 19, False, 5.9}
# if "Carla" in info:
# print("Carla is present.")
# else:
# print("Carla is absent.")
# Dictionary : dictionary are unordered after python 3.7 its become ordered
# dic = {
# "name": "gaurav",
# "id": 12345,
# }
# print(type(dic), dic)
# accessing single value
# info = {"name": "Karan", "age": 19, "eligible": True}
# print(info["name"])
# print(info.get("name"))
# Accessing multiple values: We can print all the values in the dictionary using values() method.
# info = {"name": "Karan", "age": 19, "eligible": True}
# print(info.values()) # dict_values(['Karan', 19, True])
# Accessing keys: We can print all the keys in the dictionary using keys() method.
# info = {"name": "Karan", "age": 19, "eligible": True}
# print(info.keys()) # dict_keys(['name', 'age', 'eligible'])
# Accessing key-value pairs: We can print all the key-value pairs in the dictionary using items() method.
# info = {"name": "Karan", "age": 19, "eligible": True}
# print(info.items()) # dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
# Dictionary Methods
# info = {"name": "Karan", "age": 19, "eligible": True}
# print(info)
# The update() method updates the value of the key provided to it if the item already exists in the dictionary, else it creates a new key-value pair.
# info.update({"age": 20})
# info.update({"DOB": 2001})
# print(info)
# info.clear() # The clear() method removes all the items from the list.
# print(info)
# info.pop(
# "eligible"
# ) # The pop() method removes the key-value pair whose key is passed as a parameter.
# print(info)
# info.popitem() # The popitem() method removes the last key-value pair from the dictionary.
# print(info)
# del info["age"] # we can also use the del keyword to remove a dictionary item.
# print(info)
# del info # If key is not provided, then the del keyword will delete the dictionary entirely.
# print(info)
# for loop with else
# for i in range(0):
# print(i)
# else:
# print("no i bitch")
# here see that on loop break the else does not work
# for i in range(6):
# print(i)
# if i == 4:
# break
# else:
# print("lopps break")
# while loop with else
# i = 0
# while i < 7:
# print(i)
# i = i + 1
# if i == 4:
# break
# else:
# print("Sorry no i")
# Exception Handling
# try:
# statements which could generate
# exception
# except:
# Soloution of generated exception
# example
# try:
# num = int(input("Enter an integer: "))
# except ValueError:
# print("Number entered is not an integer.")
# except IndexError:
# print("Index Error")
# Finally Clause : The finally code block is also a part of exception handling. When we handle exception using the try and except block, we can include a finally block at the end. The finally block is always executed, so it is generally used for doing the concluding tasks like closing file resources or closing database connection or may be ending the program execution with a delightful message.
# try:
# statements which could generate
# exception
# except:
# solution of generated exception
# finally:
# block of code which is going to
# execute in any situation
# example
# try:
# num = int(input("Enter an integer: "))
# except ValueError:
# print("Number entered is not an integer.")
# finally:
# print("This block is always executed.")
# Raising Custom errors : In python, we can raise custom errors by using the raise keyword.
# salary = int(input("Enter salary amount: "))
# if not 2000 < salary < 5000:
# raise ValueError("Not a valid salary")
# python error classes : https://docs.python.org/3/library/exceptions.html
# short hand if else
# If ... Else in One Line
# There is also a shorthand syntax for the if-else statement that can be used when the condition being tested is simple and the code blocks to be executed are short. Here's an example:
# 1)
# a = 2
# b = 330
# print("A") if a > b else print("B")
# 2)
# a = 330
# b = 330
# print("A") if a > b else print("=") if a == b else print("B")
# result = value_if_true if condition else value_if_false
# or
# if condition:
# result = value_if_true
# else:
# result = value_if_false
# Enumerate function in python : The enumerate function is a built-in function in Python that allows you to loop over a sequence (such as a list, tuple, or string) and get the index and value of each element in the sequence at the same time. Here's a basic example of how it works:
# Loop over a list and print the index and value of each element
# fruits = ["apple", "banana", "mango"]
# for index, fruit in enumerate(fruits):
# print(index, fruit)
# output :
# 0 apple
# 1 banana
# 2 mango
# Loop over a string and print the index and value of each character
# s = "hello"
# for index, c in enumerate(s):
# print(index, c)
# https://replit.com/@codewithharry/43-Day43-Virtual-Environment#.tutorial/Tutorial.md
# Virtual Environment : A virtual environment is a tool used to isolate specific Python environments on a single machine, allowing you to work on multiple projects with different dependencies and packages without conflicts. This can be especially useful when working on projects that have conflicting package versions or packages that are not compatible with each other.
# To create a virtual environment in Python, you can use the venv module that comes with Python. Here's an example of how to create a virtual environment and activate it:
# # Create a virtual environment
# python -m venv myenv
# # Activate the virtual environment (Linux/macOS)
# source myenv/bin/activate
# # Activate the virtual environment (Windows)
# myenv\Scripts\activate.bat
# Once the virtual environment is activated, any packages that you install using pip will be installed in the virtual environment, rather than in the global Python environment. This allows you to have a separate set of packages for each project, without affecting the packages installed in the global environment.
# To deactivate the virtual environment, you can use the deactivate command:
# # Deactivate the virtual environment
# deactivate
# The "requirements.txt" file
# In addition to creating and activating a virtual environment, it can be useful to create a requirements.txt file that lists the packages and their versions that your project depends on. This file can be used to easily install all the required packages in a new environment.
# To create a requirements.txt file, you can use the pip freeze command, which outputs a list of installed packages and their versions. For example:
# # Output the list of installed packages and their versions to a file
# pip freeze > requirements.txt
# To install the packages listed in the requirements.txt file, you can use the pip install command with the -r flag:
# # Install the packages listed in the requirements.txt file
# pip install -r requirements.txt
# Using a virtual environment and a requirements.txt file can help you manage the dependencies for your Python projects and ensure that your projects are portable and can be easily set up on a new machine.
# Import
# import math # import
# result = math.sqrt(9)
# print(result) # Output: 3.0
# from math import sqrt, pi # from keyword
# result = sqrt(9)
# print(result) # Output: 3.0
# print(pi) # Output: 3.141592653589793
# from math import * # import everything
# result = sqrt(9)
# print(result) # Output: 3.0
# print(pi) # Output: 3.141592653589793
# import math as m # as keyword
# result = m.sqrt(9)
# print(result) # Output: 3.0
# print(m.pi) # Output: 3.141592653589793
# import math # The dir function
# print(dir(math))
# https://replit.com/@codewithharry/45-Day45-if-name-main-in-Python#.tutorial/Tutorial.md
# importing other files and it runs function
# os module
# https://replit.com/@codewithharry/46-Day-46-os-Module#.tutorial/Tutorial.md
# os module is vast and awesome
# global and local variable and how to manage them
# https://replit.com/@codewithharry/48-Day48-local-vs-global-variables#main.py
# File IO
# https://replit.com/@codewithharry/49-Day49-File-IO#.tutorial/Tutorial.md
# READING A FILE
# f = open("myfile.txt", "r")
# print(f)
# text = f.read()
# print(text)
# f.close()
# WRITING A FILE
# f = open('myfile.txt', 'a')
# f.write('Hello, world!')
# f.close()
# do not have to use with
# with open('myfile.txt', 'a') as f:
# f.write("Hey I am inside with")
# readlines() method : The readline() method reads a single line from the file. If we want to read multiple lines, we can use a loop.
# The readlines() method reads all the lines of the file and returns them as a list of strings.
# f = open("myfile.txt", "r")
# while True:
# line = f.readline()
# if not line:
# break
# print(line)
# writelines() method : The writelines() method in Python writes a sequence of strings to a file. The sequence can be any iterable object, such as a list or a tuple.
# f = open("myfile.txt", "w")
# lines = ["line 1\n", "line 2\n", "line 3\n"]
# f.writelines(lines)
# f.close()
# Keep in mind that the writelines() method does not add newline characters between the strings in the sequence. If you want to add newlines between the strings, you can use a loop to write each string separately:
# f = open("myfile.txt", "w")
# lines = ["line 1", "line 2", "line 3"]
# for line in lines:
# f.write(line + "\n")
# f.close()
# seek() function : The seek() function allows you to move the current position within a file to a specific point. The position is specified in bytes, and you can move either forward or backward from the current position. For example:
# with open("file.txt", "r") as f:
# # Move to the 10th byte in the file
# f.seek(10)
# # Read the next 5 bytes
# data = f.read(5)
# print(data)
# tell() function : The tell() function returns the current position within the file, in bytes. This can be useful for keeping track of your location within the file or for seeking to a specific position relative to the current position. For example:
# with open("file.txt", "r") as f:
# # Read the first 10 bytes
# data = f.read(10)
# # Save the current position
# current_position = f.tell()
# # Seek to the saved position
# print(f.seek(current_position)) # gives index of current location output: 10
# truncate() function : The truncate() function allows you to shorten a file to a specific size when opened in write mode ('w' or 'a') with Python's open function.
# with open("sample.txt", "w") as f:
# f.write("Hello World!")
# f.truncate(5)
# with open("sample.txt", "r") as f:
# print(f.read())
# Lambda Functions in Python : In Python, a lambda function is a small anonymous function without a name. It is defined using the lambda keyword and has the following syntax:
# Function to double the input
# def double(x):
# return x * 2
# Lambda function to double the input
# lambda x: x * 2
# Function to calculate the product of two numbers
# def multiply(x, y):
# return x * y
# Lambda function to calculate the product of two numbers
# lambda x, y: x * y
# Lambda function to calculate the product of two numbers,
# with additional print statement
# lambda x, y: print(f"{x} * {y} = {x * y}")
# Lambda functions are often used in situations where a small function is required for a short period of time. They are commonly used as arguments to higher-order functions, such as map, filter, and reduce.
# def appl(fx, value):
# return 6 + fx(value)
# double = lambda x: x * 2
# cube = lambda x: x * x * x
# avg = lambda x, y, z: (x + y + z) / 3
# print(double(5))
# print(cube(5))
# print(avg(3, 5, 10))
# print(appl(lambda x: x * x, 2))
# Map, Filter and Reduce in Python
# map
# l = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# double = lambda x: x + x
# ans = list(map(double, l))
# print(ans, type(ans))
# filter
# divisibleBy3 = lambda y: y % 3 == 0
# ans2 = list(filter(divisibleBy3, l))
# print(ans2, type(ans2))
# reduce
# from functools import reduce
# List of numbers
# numbers = [1, 2, 3, 4, 5]
# # Calculate the sum of the numbers using the reduce function
# sum = reduce(lambda x, y: x + y, numbers)
# # Print the sum
# print(sum)
# 'is' vs '==' in Python
# is: Checks object identity (same object in memory).
# ==: Checks object value equality (same content).
# Use:
# ==: For comparing object values (most common).
# is: For checking if objects are the same object (rarely needed).
# a = None
# b = None
# print(a is b) # exact location of object in memory
# print(a is None) # exact location of object in memory
# print(a == b) # value
# a = [1, 2, 3]
# b = [1, 2, 3]
# print(a == b) # True
# print(a is b) # False
# a = "hello"
# b = "hello"
# print(a == b) # True
# print(a is b) # True
# a = 5
# b = 5
# print(a == b) # True
# print(a is b) # True
# computer= R P S
# 0 1 2
# player= R 0 D L W
# P 1 W D L
# S 2 L W D
caseMatrix = [["Draw", "Lose", "Win"], ["Win", "Draw", "Lose"], ["Lose", "Win", "Draw"]]
p = int(input(" Enter 0 for Rock :\n Enter 1 for Paper : \n Enter 2 for Paper : \n \t"))
import random
# Generate a random number between 0 and 2:
c = random.randint(0, 2)
# print(c)
print("result :", caseMatrix[p][c])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment