You are on page 1of 10

1.

Python – General Purpose Language – Use in ML, GUI, Software Development, Web
Development everywhere. Interpreted, Object-Oriented, high-level language. It also
supports procedural oriented. Current version 3.10
2. What’s new in 3.10
a. Match-case-other
total = (first_variable
+ second_variable
- third_variable)
Understand the match case more - https://learnpython.com/blog/python-
match-case-statement/
https://realpython.com/python310-new-features/
3. Pep-8 standard
• Pep8 is a coding standard and Style Guide for readability and long-term
maintainability
• PEP 8 suggests lines should be limited to 79 characters
o Use 4 consecutive spaces to indicate indentation.
o Prefer spaces over tabs
o Line break
▪ Python will assume line continuation if code is contained within
parentheses, brackets, or braces. Break after comma
▪ Use backslash \ in import, string
▪ If line breaking needs to occur around binary operators, like + and *
it should occur before the operator
▪ Comments:
• Start each line with a # followed by a single space.
• Separate paragraphs by a line containing a single #
• Separate inline comments by two or more spaces from the
statement
▪ Docstring ‘’’ ‘’’ or “”” “””
▪ Whitespace Around Binary Operators
• Function, Method - Use a lowercase word or words, separate words by underscores
• Class - Start each word with a capital letter. Do not separate words with
underscores
• Variable - Use a lowercase single letter, word, or words, separate words by
underscores
• Constant - Use an uppercase single letter, word, or words, separate words by
underscores
• Package - Use a short, lowercase word or words. Do not separate words with
underscores
• Surround top-level functions and classes with two blank lines
• Surround method definitions inside classes with a single blank line
• Use blank lines sparingly inside functions to show clear steps (One at a time)
4. __init__.py helps the Python interpreter to recognise the folder as package. It also
specifies the resources to be imported from the modules. If the __init__.py is empty
this means that all the functions of the modules will be imported. We can also specify
the functions from each module to be made available.
5. What is module in Python? A file containing python code
6. Data types in Python
a. None
b. Numeric (int, float, complex, bool)
c. List
d. Tuple
e. Set – {1,2,3} To store unique values. Set items are unordered, unchangeable,
and do not allow duplicate values. set cannot have mutable items like list.
a = set(). a = {} is dict. 'set' object does not support indexing. Useful in union
etc. Can be used in loops.
f. String
g. Range
h. Dictionary
7. Operators in Python
a. Arithmetic operators - +, -, *, /, //, %, **
b. Assignment operators - =, +=, -=, *=, /=, %=, //=, **=, &=, |=, ~=, ^=, >>=,
<<=
c. Comparison operators - >, <, ==, !=, >=, <=
d. Logical operators - and, or, not
e. Identity operators - is, is not (print(a is not b) - returns true or false)
f. Membership operators - in, not in
g. Bitwise operators - &, |, ~, ^, >>, <<
8. String formatting
a. “Old Style” String Formatting (% Operator)
i. '%s' % str1
ii. 'Hey %s, there is a 0x%x error!' % (name, errno)
iii. 'Hey %(name)s, there is a 0x%(errno)x error!' % {"name": name, "errno":
errno }
b. “New Style” String Formatting (str.format)
txt1 = "My name is {fname}, I'm
{age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
print('{2} {1} {0}'.format('directions', 'the',
'Read'))
c. f string
d. Template class for user supplied format strings
9. Last item in list
10. Print 2nd item from the last in a list or tuple
11. Difference between List and Tuple
12. Can we have a list with different data types?
13. Swap two numbers in single line?
14. Swap 2 numbers using arithmetic operators?
15. Copy, Shallow Copy and Deep Copy
a. = is just reference
b. Shallow copy – makes a different copy of immutable objects but not mutable
objects lists inside list
c. Deep copy – makes a separate copy of all import copy…. Copy.deepcopy(list)
16. List append(value), insert(index, value), remove(value)-removes first occurrence, pop-last
element, pop(index), del list[:2] delete range
17. What is Array in Python? Similar like list but it can hold only same data type
18. Difference between Array and List. Array more impact in memory
19. Numpy is more advanced than array. Helpful in matrix and related functions
20. Dictionary – get a value using key but shouldn’t throw error if the key is not available –
use get(key), get(key, ‘custom message’)
21. Dict from 2 lists - dict(zip(a, b))
22. Dictionary del dict[key]
23. Can we have list inside dictionary
24. Address a=10, b=10, print(id(a)), print(id(b))
25. Data which is not tagged to any variable – Garbage collection – later
26. Do we have constant in Python? No. but show our intentions using CAPS – e.g. PI
27. What split function will return in python
28. Recursive and Match Case
def sum_of_numbers(numbers):
if len(numbers) == 0:
return 0
else:
return numbers[0] + sum(numbers[1:])

def sum_list(numbers):
match numbers:
case []:
return 0
case [first, *rest]:
return first + sum_list(rest)
29. Math function sqrt, pow
30. Print a pattern print(‘#’, end=’’) – Pyramid, 1 to 5 or 5 to 1
31. For…break…else ... If break not executed else part of for will be executed
a. Prime number without flag (a number that can be divided exactly only by itself
and 1)
32. Find square of all numbers in the list a = [5, 6, 7], b = [i*i for i in a]
33. math.sqrt
34. Functions -pass by value or pass by reference? None.
a. Values are passed to function by object reference. if object is immutable (not
modifiable) than the modified value is not available outside the function. if
object is mutable (modifiable) than modified value is available outside the
function
35. eval() function parse the expression argument and evaluate and run it as a python
expression
36. Types of arguments
a. default arguments - def add(a,b=5)
b. keyword arguments - add(b=10,a=20)
c. positional arguments - add(a,b,c)
d. Variable length
i. arbitrary positional arguments (Variable-length arguments) add(*b) -
pass variable number of arguments. zero or more
ii. arbitrary keyword arguments (Variable-length arguments) fn(**a) - can
hold keyword variable-length arguments (pass like keyword arg, output
is dictionary)
37. Local vs Global variable – Preference to local variable
38. If we want to use global inside a block use keyword global
a = 10
def fn():
global a
a = 15
print(a)
fn()
print(a)
39. Use both local and global
a = 10
def fn():
a = 8
globals()['a'] = 15
print(a)
fn()
print(a)
40. Can a python function return multiple values?
41. Fibonacci series - a series of numbers in which each number ( Fibonacci number ) is the
sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc
42. Recursion - a defined function can call itself
43. Max recursion limit: 1000, sys.getrecursionlimit(), sys.settrecursionlimit()
44. Factorial using loop and recursive. Fact of zero is 1
45. iter - l = [4,5,6] i = iter(l) print(i.__next__()) or print(next(it))
46. Anonymous function or lamda - Only one expression
a. f = lambda a,b : a+b or f = lambda a : a*a - f(5)
b. filter is a built-in function that allows you to process an iterable and extract
those items that satisfy a given condition
i. Get even numbers l = [3, 5, 7, 8]
evens = list(filter(lambda n : n%2 == 0,l))
c. Map in Python is a function that works as an iterator to return a result after
applying a function to every item of an iterable (tuple, lists, etc.).
i. doubles = list(map(lambda n : n + n, evens))
47. Python function itself an object. One function name can be assigned to another
a. def f1(): f2=f1
48. Decorators allow us to wrap one function with another function in order to extend the
behavior of the wrapped function, without permanently modifying it
49. Class - All the variables and the methods in the code are public by default
50. Class Variable (aka Static variables) – Common for all methods, Instance variable –
defined inside __init__ and separate for all instances
51. Can I access instance variable from a sub class? Yes. Use self. Directly
52. How to print all instance attributes – use obj.__dict__
53. Self - The self parameter is a reference to the current instance of the class, and is used
to access variables/functions that belongs to the class
54. Python __repr__() function returns the object representation in string format
55. Classmethod - @classmethod pass cls instead of self. If you accessing only class
variables in a method we can use this
56. Staticmethod – if we are not using class or instance variables
57. Innerclass aska nestedclass – Class inside class – Generally avoid. Understanding
purpose since they are closely linked together. Object of inner class can be created
inside the outer class or even outside the outer class
58. Inheritance – Single, Multiple, Multilevel, Hierarchical
a. super().__init__() – Calling parent init if sub have its own init. If sub doesn’t have
then parent inti automatically called. Super(0 can be used to access other parent
attributes too
b. In multiple inheritance Method Resolution Order (MRO) is followed. Super() will
indicate the first parent
c. subclas s can access all properties of superclass but not vice versa
59. Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data
types).
a. Duck Typing - the code itself does not care about whether an object is a duck,
but instead it does only care about whether it quacks. Same function in parent
and child classes.
b. Operator overloading - We can change the meaning of an operator in Python
depending upon the operands used. For e.g. __add__ use this method inside
the class and add two objects instance variables. So when we use obj1 + obj2
the add method automatically called. For greater than use __gt__
c. Method overloading – same method name with different number of arguments
d. method overriding – Overwrides parent method.
60. Encapsulation: Wrapping data and the methods that work on data within one unit. This
puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can
only be changed by an object’s method. Those types of variables are known as private
variables. Private variable use __ e.g. __c = 6 or __fun():
61. Abstract Class - Only declaration not defenition. Its not availbale in Python. We can use
abc class to schieve this. from abc import ABC, abstractmethod. class A(ABC):
use@abstractmethod above method names. Forcing child to implement methods
required.
62. Exceptions: Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program
a. try-except-else-finally
b. import sys module to get type of exception. except Exception as e: print
e.__class__
c. catch specific errors – ZeroDivisionError, KeyError
d. raise ValueError("")
63. Thread - A thread is a separate flow of execution
a. from threading import *, Inherit Thread class inside a class, implement run
function inside the class... but when calling obj1.start() - internally it will call run.
joining - obj1.join, obj2.join then main code
b. another option
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
c. threading.current_thread().name)-prints name of the thread
64. Files
file = open("file.txt", "r")
file.readline()
print (file.read())
file.read(5) 5 - no.of char
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

with open("file.txt", 'r') as file:


data = file.read()

copying image
rb - read binary
wb- write binary
65. Command line argument import sys …. sys.argv
66. Binary Search – divide by mid and check. Only on sorted
67. Bubble sort - Swap first 2 then 2nd and 3rd etc. last we get highest in the right most.
Repeat same – leads to multiple swapping
68. Selection sort - Keep a variable min or max index. at the end swap
69. Parsing – xml and json data = json.load(f)
a. <Page key="Networking_WirelessConfig"
relative_path="set_config_network_Wifi.html?tab=Networking&amp;menu=Net
Wireless" expected_element="WirelessList">
b. <Elements>
c. <Element key="WirelessList" id="wifiScanList" name="" xpath="" class=""
type="" />
d. <Element key="WirelessEnable" id="" name="WirelessEnable" xpath=""
class="" type="" />
e. <Element key="" id="" name=""
xpath=""/html/body/div/table/tbody/tr[4]/td[2]/div[3]/table/tbody/tr[5]/td[2]""
class="" type="" />
f. </Elements>
g. </Page>
70. Regular expression
a. findall Returns a list containing all matches
b. search Returns a Match object if there is a match anywhere in the string
c. split Returns a list where the string has been split at each match
d. sub Replaces one or many matches with a string
71. Programs
a. What are Dict and List comprehensions?
i. Dictionary and list comprehensions are just another concise way to
define dictionaries and lists.
ii. x=[i for i in range(5)]
iii. x=[i : i+2 for i in range(5)]
b. 2nd highest in an array
c. Sort the following
list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
Sort…
72. Find duplicates
a = 'sjshgdkjsosadasdkl;dl'
b = {}
for i in a:
if i not in b.keys():
b[i] = 1
else:
b[i] += 1
print(b)
73. Split characters and find unique
a = 'sjshgdkjsosadasdkl;dl'
b = set([x for x in a]) or b = set([*a])
print(b)
74.
75. Selenium
a. Web Driver - ChromeDriver, geckodriver, safaridriver and msedgedriver, opera
and IE
b. Location of the webdriver
c. Components of Selenium IDE, Selenium RC, Selenium Web driver, Selenium GRID
d. current selenium version 4
e. How do you install selenium in windows and Linux and Mac
from selenium import webdriver
driver = webdriver.Firefox()
driver.set_page_load_timeout()
driver.get("https://google.co.in / search?q =
geeksforgeeks")
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_cert = True

profile.set_preference("browser.download.folderList", 2)
proxy = Proxy({'proxyType': ProxyType.MANUAL, 'httpProxy':
myproxy, 'noProxy': ''})
self.driver = webdriver.Firefox(firefox_profile=profile,
proxy=proxy)
f. Find elements
element = driver.find_element(By.ID,"passwd-id")
elements = driver.find_elements(By.NAME, "passwd")
find_element_by_id() - name, xpath
find_elements_by_name() - xpath, link-text, css - no IDs
which is practically unique
a. Find xpath – live example
b. Others
element.clear()
element.send_keys("some text")
element.send_keys(" and some", Keys.ARROW_DOWN) - Simulating
pressing keys
elem.send_keys(Keys.RETURN)
self.driver.close()
c.
d. Implicit Wait - driver.implicitly_wait(10) - default is 0
e. Explicit Wait
An explicit wait is a code you define to wait for a certain condition to occur
before proceeding further in the code. The extreme case of this is time.sleep(),
which sets the condition to an exact time period to wait. There are some
convenience methods provided that help you write code that will wait only as
long as required. WebDriverWait in combination with ExpectedCondition is one
way this can be accomplished.
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.link_text, "Courses"))
title_is
title_contains
presence_of_element_located
visibility_of_element_located
visibility_of
presence_of_all_elements_located
text_to_be_present_in_element
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
invisibility_of_element_located
element_to_be_clickable
staleness_of
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present
f. Action Chains in Selenium Python
ActionChains are a way to automate low-level interactions such as mouse
movements, mouse button actions, keypress, and context menu interactions.
This is useful for doing more complex actions like hover over and drag and drop

action.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONT
ROL).perform()
BACKSPACE
DOWN
F10
SPACE
TAB
SHIFT
CONTROL
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Firefox()
action = ActionChains(driver)
action.click(on_element = element)
action.perform()

click
click_and_hold
context_click
double_click
drag_and_drop
drag_and_drop_by_offset
key_down
key_up
move_by_offset
move_to_element
move_to_element_with_offset
perform
pause
release
reset_actions
send_keys

g. Name few Selenium Exceptions


i. ElementClickInterceptedException
ii. ElementNotInteractableException
iii. ElementNotVisibleException
iv. NoSuchFrameException
v. TimeoutException
h. Cookie
i. driver.get_cookie("foo")driver.get_cookie("foo")
ii. driver.delete_cookie("foo")
i. back and forward
i. driver.back()
ii. driver.forward()
j. Second tab Open and Switch
i. browser.execute_script("window.open('about:blank', 'tab2');")
ii. browser.switch_to.window("tab2")
iii. browser.get('http://bing.com')
k. Execute Script - allows to execute JavaScript passed as string argument
l. Wait for an alert
element = WebDriverWait(self.driver,
self.time_out).until(ec.alert_is_present())
m. Accept alert - alert = self.driver.switch_to.alert, alert.accept()
n. Checkbox
o. Drop Down
i. select_by_visible_text(text)
ii. element.select_by_value(value)
p. Table
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows:
col = row.find_elements(By.TAG_NAME, "td")[1]
print col.text
q. Search page
i. page_source = self.driver.page_source
ii. result = re.search(search_text, page_source)
r. Wait for an element in the page (when page load is not working)
s. Toast Message
i. message = WebDriverWait(self.driver,
30).until(ec.presence_of_element_located((By.CSS_SELECTOR, ".md-
toast-content")))
ii. status = WebDriverWait(self.driver,
30).until(ec.text_to_be_present_in_element((By.CSS_SELECTOR, ".md-
toast-content"), search_text))
t. Scroll to element
i. actions.moveToElement(element)
ii. driver.execute_script("arguments[0].scrollIntoView();", element)
76. API
a. CRUD – Create, Retrieve, Update and Delete
b. What are the HTTP methods available and uses?
i. 1. Get
ii. 2. post-Create a new record
iii. 3. Put - Update/Create
iv. 4. Delete –
v. Patch – partial update
c. Input
i. requests.get(uri, verify=False, proxies={'http': '', 'https': ''}, timeout=5)
ii. verify - to verify TLS certificate
iii. timeout - how many seconds to wait for the client to make connection
iv. headers - dict of http headers
v. cert - cert file (strig or tuple)
vi. params - dict, list or tuple - query string
d. Output
i. status_code
ii. content - content in bytes
iii. json() - resturns json object of result
iv. text - contents of the response
v. close()
e. Authorization is the process of giving access to someone. If you are Authorized
then you have access to that resource. Now to Authorize you to need to present
credentials and as we discussed earlier that process is called Authentication
f. Status Code
i. 200 - ok - Successful Post request
• 201 - new resource created
• 400 - Bad Request
• 404 - Not found
• 401 - Unauthorised
• 403 - Forbidden
• 500 - Internal Server error

You might also like