├── .idea
├── .gitignore
├── Python-Beginner.iml
├── inspectionProfiles
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── 100_codingquestion.py
├── 10_datatypes.py
├── 11_operators.py
├── 12_numbersystemconversion.py
├── 13_swapvariablevalues.py
├── 14_bitwiseoperator.py
├── 15_mathfunctions.py
├── 16_userinput.py
├── 17_ifelse.py
├── 18_whileloop.py
├── 19_forloop.py
├── 1_division.py
├── 20_breakcontinuepass.py
├── 21_forelse.py
├── 22_array.py
├── 23_dynamicarray.py
├── 24_arrayfunctions.py
├── 25_arrayadvance.py
├── 26_matrix.py
├── 27_function.py
├── 28_functionarguments.py
├── 29_typesofarguments.py
├── 2_power.py
├── 30_globalandlocalvariable.py
├── 31_listasparameter.py
├── 32_recursion.py
├── 33_anonymousfunction.py
├── 34_decorator.py
├── 35_module.py
├── 36_specialvariable.py
├── 37_classandobject.py
├── 38_initmethod.py
├── 39_typesofvariables.py
├── 3_modulus.py
├── 40_typesofmethods.py
├── 41_innerclass.py
├── 42_singleinheritance.py
├── 43_multilevelinheritance.py
├── 44_multipleinheritance.py
├── 45_constructorininheritance.py
├── 46_polyducktyping.py
├── 47_polyoperatoroverloading.py
├── 48_methodoverloading.py
├── 49_methodoverriding.py
├── 4_printstring.py
├── 50_iterator.py
├── 51_generator.py
├── 52_exceptionhandling.py
├── 53_multithreading.py
├── 54_file.py
├── 55_linearsearch.py
├── 56_binarysearch.py
├── 57_bubblesort.py
├── 58_selectionsort.py
├── 59_zipfunction.py
├── 5_stringvariable.py
├── 60_insertionsort.py
├── 61_mergesort.py
├── 62_stack.py
├── 63_readexceldata.py
├── 64_queue.py
├── 65_dequeue.py
├── 66_loadjsonstring.py
├── 67_loadjsonfile.py
├── 68_dumpjsonasstring.py
├── 69_dumpjsonasjsonfile.py
├── 6_lists.py
├── 70_codingquestion.py
├── 71_codingquestion.py
├── 72_codingquestion.py
├── 73_codingquestion.py
├── 74_codingquestion.py
├── 75_codingquestion.py
├── 76_codingquestion.py
├── 77_codingquestion.py
├── 78_codingquestion.py
├── 79_codingquestion.py
├── 7_tuple.py
├── 80_codingquestion.py
├── 81_codingquestion.py
├── 82_codingquestion.py
├── 83_codingquestion.py
├── 84_codingquestion.py
├── 85_codingquestion.py
├── 86_codingquestion.py
├── 87_codingquestion.py
├── 88_codingquestion.py
├── 89_codingquestion.py
├── 8_dictionary.py
├── 90_codingquestion.py
├── 91_codingquestion.py
├── 92_codingquestion.py
├── 93_codingquestion.py
├── 94_codingquestion.py
├── 95_codingquestion.py
├── 96_codingquestion.py
├── 97_codingquestion.py
├── 98_codingquestion.py
├── 99_codingquestion.py
├── 9_memoryaddofvariable.py
├── calc.py
├── introduction
├── introduction1
├── me.jpg
├── me1.jpg
├── point1.json
└── test.xlsx
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/Python-Beginner.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/100_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | result = [x for i, x in enumerate(range(10)) if i % 3 == 0]
4 |
5 | print(result)
6 |
7 | # OUTPUT
8 | # [0, 3, 6, 9]
9 |
--------------------------------------------------------------------------------
/10_datatypes.py:
--------------------------------------------------------------------------------
1 |
2 | # numeric - int | float | complex | bool
3 |
4 | num = 1410
5 | print(type(num)) #
6 |
7 | num = 14.10
8 | print(type(num)) #
9 |
10 | num = 6 + 9j
11 | print(type(num)) #
12 |
13 | # convert float to int
14 | num = 14.10
15 | print(int(num)) # 14
16 |
17 | # convert int to float
18 | num = 14
19 | print(float(num)) # 14.0
20 |
21 | # convert int values to complex
22 | num = 14
23 | num1 = 10
24 | print(complex(num, num1)) # (14+10j)
25 |
26 | result = num > num1
27 | print(type(result)) #
28 |
29 | # convert bool to int means True should be 1 and False should be 0
30 | print(int(True)) # 1
31 | print(int(False)) # 0
32 |
33 | s = {10, 20, 30, 40, 50}
34 | print(type(s)) #
35 |
36 | print(range(10)) # range(0, 10)
37 | print(type(range(10))) #
38 | print(list(range(10))) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
39 | print(list(range(2, 10, 2))) # [2, 4, 6, 8]
40 |
--------------------------------------------------------------------------------
/11_operators.py:
--------------------------------------------------------------------------------
1 |
2 | # Arithmatic | Assignment | Relational | Logical | Unary
3 | # Arithmatic Operator
4 |
5 | x = 14
6 | y = 10
7 |
8 | print(x + y) # 24
9 | print(x - y) # 4
10 | print(x * y) # 140
11 | print(x / y) # 1.4
12 | print(x % y) # 4
13 |
14 | # Assignment Operator
15 |
16 | x = x + 2
17 | print(x) # 16
18 |
19 | x += 1
20 | print(x) # 17
21 |
22 | num, num1 = 14, 10
23 | print(num) # 14
24 | print(num1) # 10
25 |
26 | # Unary Operator
27 |
28 | num = -num
29 | print(num) # -14
30 |
31 | print(num < num1) # True
32 | print(num > num1) # False
33 | print(num == num1) # False
34 | print(num <= num1) # True
35 | print(num >= num1) # False
36 | print(num != num1) # True
37 |
38 | # Logical Operator
39 |
40 | num = 14
41 | num1 = 10
42 | print(num > 13 and num1 < 11) # True
43 | print(num > 13 and num1 < 10) # False
44 | print(num > 13 or num < 10) # True
45 |
46 | x = num > 13 and num1 < 11
47 | print(not x) # False
48 |
--------------------------------------------------------------------------------
/12_numbersystemconversion.py:
--------------------------------------------------------------------------------
1 |
2 | # Decimal | Binary | Octal | Hexadecimal
3 |
4 | print(bin(14)) # 0b1110 0b represents binary and 1110 is the binary number of 14
5 | print(0b1110) # 14 converts binary into decimal
6 |
7 | print(oct(14)) # 0o16 0o represents octal and 16 is the octal number of 14
8 |
9 | print(hex(14)) # 0xe 0x represents hexa and e is the hexadecimal number of 14
10 |
--------------------------------------------------------------------------------
/13_swapvariablevalues.py:
--------------------------------------------------------------------------------
1 |
2 | x = 14
3 | y = 10
4 |
5 | x, y = y, x
6 |
7 | print('x = ' + str(x))
8 | print('y = ' + str(y))
9 |
--------------------------------------------------------------------------------
/14_bitwiseoperator.py:
--------------------------------------------------------------------------------
1 |
2 | # ~ compliment
3 | x = 14
4 | # Binary of 14 is 00001110
5 | # Compliment of above number is reverse of binary number that is 11110001
6 | print(~x) # -15
7 | # How come -15?
8 | # Binary of 15 is 00001111
9 | # Now 1s compliment of above number is 11110000
10 | # Add 1 in above number to get 2s compliment that is 11110001 which equals -15
11 |
12 | # Bitwise AND operator
13 | print(14 & 10) # 10
14 | # 14 00001110
15 | # 10 00001100
16 | # -------------
17 | # 00001100 We get 1 when both are 1
18 |
19 | # Bitwise OR operator
20 | print(14 | 10) # 14
21 | # 14 00001110
22 | # 10 00001100
23 | # -------------
24 | # 00001110 We get 1 when any of is 1
25 |
26 | # Bitwise XOR operator
27 | print(14 ^ 10) # 4
28 | # 14 00001110
29 | # 10 00001100
30 | # -------------
31 | # 00000010 We get 1 when both bits are not same
32 |
33 | # Left Shift Operator
34 | print(14 << 1) # 28
35 | # 14 1110.000
36 | # shift 1 digit 11100.00 that is 28
37 |
38 | # Right Shift Operator
39 | print(14 >> 2) # 3
40 | # 14 1110.000
41 | # shift 1 digit 11.100 that is 3
42 |
--------------------------------------------------------------------------------
/15_mathfunctions.py:
--------------------------------------------------------------------------------
1 | import math
2 | # import math as m (we can use math as well as m)
3 | # from math import sqrt, pow (import specific functions only)
4 |
5 | print(math.sqrt(25)) # Square Root - 5.0
6 | print(math.floor(14.6)) # 14
7 | print(math.ceil(14.2)) # 15
8 | print(math.pow(5, 3)) # 125.0
9 | print(math.pi) # 3.141592653589793
10 | print(math.e) # 2.718281828459045
11 |
--------------------------------------------------------------------------------
/16_userinput.py:
--------------------------------------------------------------------------------
1 | x = input("Enter 1st number:") # input always gives value in str
2 | y = input("Enter 2nd number:")
3 |
4 | z = int(x) + int(y)
5 |
6 | print(z)
7 |
8 | ch = input("Enter a character:")
9 | print(ch)
10 | print(ch[0]) # print first character if more than one character is provided
11 |
12 |
13 | result = eval(input("Enter an expression:")) # e.g 2 + 3 - 1
14 | print(result)
15 |
--------------------------------------------------------------------------------
/17_ifelse.py:
--------------------------------------------------------------------------------
1 | num = 14
2 | mod = num % 2
3 |
4 | if mod == 0:
5 | print("Even")
6 | if num > 10: # nested if
7 | print("Bigger Number")
8 | elif num == 10:
9 | print("Equal Number")
10 | else:
11 | print("Smaller Number")
12 | else:
13 | print("Odd")
14 |
--------------------------------------------------------------------------------
/18_whileloop.py:
--------------------------------------------------------------------------------
1 | i = 1 # Initialization
2 |
3 | while i <= 5: # Condition
4 | print("Hello Akshay")
5 | i = i + 1 # Increment
6 |
7 | # ----------------------------------------------
8 | i = 5 # Initialization
9 |
10 | while i >= 1: # Condition
11 | print("Hello Patel")
12 | i = i - 1 # Decrement
13 |
14 | # ----------------------------------------------
15 |
16 | i = 1
17 | j = 1
18 |
19 | while i <= 5:
20 | print("Hello Akshay ", end="")
21 | j = 1
22 | while j <= 5:
23 | print("Patel ", end="")
24 | j = j + 1
25 |
26 | i = i + 1
27 | print()
28 |
29 | # Hello Akshay Patel Patel Patel Patel Patel
30 | # Hello Akshay Patel Patel Patel Patel Patel
31 | # Hello Akshay Patel Patel Patel Patel Patel
32 | # Hello Akshay Patel Patel Patel Patel Patel
33 | # Hello Akshay Patel Patel Patel Patel Patel
34 |
--------------------------------------------------------------------------------
/19_forloop.py:
--------------------------------------------------------------------------------
1 | # print each value from list
2 | lst = ['Akshay', 42, 'Panth', 6]
3 |
4 | for value in lst:
5 | print(value)
6 |
7 | # print each character from string
8 |
9 | lst = 'Akshay'
10 |
11 | for ch in lst:
12 | print(ch)
13 |
14 | # print range from 1 to 9
15 |
16 | for i in range(10):
17 | print(i)
18 |
19 | # print range from 11 to 20 by skipping 2
20 |
21 | for i in range(11, 20, 2):
22 | print(i)
23 |
24 | # print range in reverse order
25 |
26 | for i in range(20, 11, -1):
27 | print(i)
28 |
--------------------------------------------------------------------------------
/1_division.py:
--------------------------------------------------------------------------------
1 |
2 | print(f'8 / 2 = 4.0 [division] { 8 / 2}')
3 | print(f'8 // 2 = 4 [integer division] {8 // 2}')
4 |
5 | '''
6 | OUTPUT
7 | 8 / 2 = 4.0 [division] 4.0
8 | 8 // 2 = 4 [integer division] 4
9 | '''
10 |
11 |
12 |
--------------------------------------------------------------------------------
/20_breakcontinuepass.py:
--------------------------------------------------------------------------------
1 | maxreq = 5
2 |
3 | userInput = int(input("Enter number of requests:"))
4 |
5 | i = 1
6 | while i <= userInput:
7 | if i > maxreq:
8 | break
9 |
10 | print("Request" + str(i))
11 | i += 1
12 |
13 | print("End")
14 |
15 | # print value from 1 to 30 except the number divisible by 3 and 5
16 |
17 | for x in range(1, 30):
18 | if x % 3 == 0 and x % 5 == 0:
19 | continue
20 |
21 | print(x)
22 |
23 | print("End")
24 |
25 | # print only in else part and skip if part
26 |
27 | for x in range(1, 10):
28 | if x % 2 == 0:
29 | pass
30 | else:
31 | print(x)
32 |
33 | print("End")
34 |
--------------------------------------------------------------------------------
/21_forelse.py:
--------------------------------------------------------------------------------
1 | # execute else part once entire for loop is done
2 |
3 | nums = [3, 6, 9, 12, 14, 18] # No number found
4 | # nums = [3, 6, 9, 12, 15, 18] # 15
5 |
6 | for num in nums:
7 | if num % 5 == 0:
8 | print(num)
9 | break
10 |
11 | else:
12 | print("No number found")
13 |
--------------------------------------------------------------------------------
/22_array.py:
--------------------------------------------------------------------------------
1 | from array import *
2 |
3 | # TypeCode CType PythonType MinSizeInBytes
4 | # 'b' signed char int 1
5 | # 'B' unsigned char int 1
6 | # 'u' Py_UNICODE unicode character 2
7 | # 'h' signed short int 2
8 | # 'H' unsigned short int 2
9 | # 'i' signed int int 2
10 | # 'I' unsigned int int 2
11 | # 'l' signed long int 4
12 | # 'L' unsigned long int 4
13 | # 'f' float float 4
14 | # 'd' double float 8
15 |
16 | vals = array('i', [2, 5, 8, 11, 18])
17 |
18 | # Get the address and size of an array
19 | print(vals.buffer_info()) # (3090525830256, 5) (address, size)
20 |
21 | for i in range(len(vals)):
22 | print(vals[i])
23 |
24 | # 2
25 | # 5
26 | # 8
27 | # 11
28 | # 18
29 |
30 | for e in vals:
31 | print(e)
32 |
33 | # 2
34 | # 5
35 | # 8
36 | # 11
37 | # 18
38 |
39 | # Print single element of an array
40 | print(vals[1]) # 5
41 |
42 | # Copy array in new array
43 |
44 | newVals = array(vals.typecode, (a for a in vals))
45 |
46 | for e in newVals:
47 | print(e)
48 |
49 | # Reverse the array
50 | vals.reverse()
51 | print(vals) # array('i', [18, 11, 8, 5, 2])
52 |
53 | # Character
54 | charArr = array('u', ['a', 'k', 's', 'h', 'a', 'y'])
55 |
56 | for e in charArr:
57 | print(e)
58 |
59 | # a
60 | # k
61 | # s
62 | # h
63 | # a
64 | # y
65 |
--------------------------------------------------------------------------------
/23_dynamicarray.py:
--------------------------------------------------------------------------------
1 | from array import *
2 |
3 | arr = array('i', [])
4 |
5 | arrLen = int(input("Enter Array Length:"))
6 |
7 | for i in range(arrLen):
8 | arrEle = int(input("Enter Array Element:"))
9 | arr.append(arrEle)
10 |
11 | print(arr)
12 |
13 | # Enter Array Length:3
14 | # Enter Array Element:10
15 | # Enter Array Element:20
16 | # Enter Array Element:30
17 | # array('i', [10, 20, 30])
18 |
--------------------------------------------------------------------------------
/24_arrayfunctions.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 |
3 | arr = array([1, 2, 3]) # numpy has different syntax, no need to pass type
4 | print(arr)
5 | # [1 2 3]
6 |
7 | arr1 = array([1, 2, 3], int) # numpy, we can give type at end if we want
8 | print(arr1)
9 | # [1 2 3]
10 |
11 | # linspace - Return evenly spaced numbers over a specified interval.
12 | arr = linspace(11, 15, 10)
13 | print(arr)
14 |
15 | # arange - Return evenly spaced values within a given interval.
16 | arr = arange(0, 9, 2)
17 | print(arr)
18 |
19 | # logspace - Return numbers spaced evenly on a log scale.0
20 | arr = logspace(0, 4, 10)
21 | print(arr)
22 | print('%2f' %arr[4])
23 |
24 | # zeros - Return a new array of given shape and type, filled with zeros.
25 | arr = zeros(5)
26 | print(arr) # [0. 0. 0. 0. 0.]
27 |
28 | # ones - Return a new array of given shape and type, filled with ones.
29 | arr = ones(5)
30 | print(arr) # [1. 1. 1. 1. 1.]
31 |
32 | # ones with int - Return a new array of given shape and type, filled with ones.
33 | arr = ones(5, int)
34 | print(arr) # [1 1 1 1 1]
35 |
--------------------------------------------------------------------------------
/25_arrayadvance.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 |
3 | arr = array([1, 2, 3, 4, 5])
4 |
5 | # Add number in each element of an array
6 | arr = arr + 5
7 | print(arr) # [ 6 7 8 9 10]
8 |
9 | arr1 = [2, 4, 6, 8, 10]
10 | # Add two different arrays
11 | arr2 = arr + arr1
12 | print(arr2) # [ 8 11 14 17 20]
13 |
14 | # Concatenate two arrays
15 | print(concatenate([arr, arr1])) # [ 6 7 8 9 10 2 4 6 8 10]
16 |
17 | print(sin(arr)) # [-0.2794155 0.6569866 0.98935825 0.41211849 -0.54402111]
18 | print(cos(arr)) # [ 0.96017029 0.75390225 -0.14550003 -0.91113026 -0.83907153]
19 | print(sum(arr)) # 40
20 | print(sqrt(arr)) # [2.44948974 2.64575131 2.82842712 3. 3.16227766]
21 | print(min(arr)) # 6
22 | print(max(arr)) # 10
23 |
24 | # Copy array
25 | # ----------
26 |
27 | # Copy - array element and memory address same
28 |
29 | arr = array([1, 3, 5, 7, 9])
30 | copyArr = arr
31 | print(copyArr) # [1 3 5 7 9]
32 | print(id(arr)) # 1531319910640
33 | print(id(copyArr)) # 1531319910640
34 |
35 | # Shallow Copy - array element is same but address is different, but if you modify one array, changes applied to both
36 |
37 | copyArr = arr.view()
38 | print(copyArr) # [1 3 5 7 9]
39 | print(id(arr)) # 1984046072048
40 | print(id(copyArr)) # 1984042661520
41 | copyArr[1] = 2
42 | print(arr) # [1 2 5 7 9]
43 | print(copyArr) # [1 2 5 7 9]
44 |
45 | # Deep Copy - array element is same but address is different, if you modify one array, changes won't be applied to both
46 |
47 | copyArr = arr.copy()
48 | print(copyArr) # [1 2 5 7 9]
49 | print(id(arr)) # 1591924195568
50 | print(id(copyArr)) # 1592199057104
51 | copyArr[1] = 3
52 | print(arr) # [1 2 5 7 9]
53 | print(copyArr) # [1 3 5 7 9]
54 |
--------------------------------------------------------------------------------
/26_matrix.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 |
3 | arr1 = array([
4 | [1, 2, 3],
5 | [4, 5, 6]
6 | ])
7 |
8 | print(arr1)
9 | # [[1 2 3]
10 | # [4 5 6]]
11 |
12 | print(arr1.dtype) # int32
13 |
14 | print(arr1.ndim) # 2 - two-dimensional array
15 |
16 | print(arr1.shape) # (2, 3) - 2 rows and 3 columns
17 |
18 | print(arr1.size) # 6 - Number of elements in an array
19 |
20 | arr2 = arr1.flatten()
21 | print(arr2) # [1 2 3 4 5 6] - Converts two(multi)-dimensional array into one-dimensional
22 |
23 | arr1 = array([
24 | [1, 2, 3, 4, 5, 6],
25 | [7, 8, 9, 10, 11, 12]
26 | ])
27 |
28 | arr2 = arr1.reshape(3, 4) # Change the dimension of an existing array
29 | print(arr2)
30 | # [[ 1 2 3 4]
31 | # [ 5 6 7 8]
32 | # [ 9 10 11 12]]
33 |
34 | arr2 = arr1.reshape(2, 2, 3) # 2 arrays with 2 rows and 3 columns
35 | print(arr2)
36 | # [[[ 1 2 3]
37 | # [ 4 5 6]]
38 | #
39 | # [[ 7 8 9]
40 | # [10 11 12]]]
41 |
42 | # Create matrix
43 | arr1 = array([
44 | [1, 2, 3, 4],
45 | [5, 6, 7, 8]
46 | ])
47 |
48 | m = matrix(arr1)
49 | print(m)
50 | # [[1 2 3 4]
51 | # [5 6 7 8]]
52 |
53 | m1 = matrix('1 2 3 4 ; 5 6 7 8')
54 | print(m1)
55 | # [[1 2 3 4]
56 | # [5 6 7 8]]
57 |
58 | m2 = matrix('1 2 3 ; 4 5 6 ; 7 8 9') # 3 rows and 3 columns
59 | print(m2)
60 | # [[1 2 3]
61 | # [4 5 6]
62 | # [7 8 9]]
63 |
64 | print(diagonal(m2)) # [1 5 9] - get all diagonal element of matrix
65 | print(m2.min()) # 1
66 | print(m2.max()) # 9
67 |
68 | # Matrix Additon
69 |
70 | m1 = matrix('1 3 5 ; 7 9 11 ; 13 15 17')
71 | m2 = matrix('2 4 6 ; 8 10 12 ; 14 16 18')
72 |
73 | m3 = m1 + m2
74 | print(m3)
75 | # [[ 3 7 11]
76 | # [15 19 23]
77 | # [27 31 35]]
78 |
79 | # Matrix Multiplication
80 | m1 = matrix('1 2 3 ; 4 5 6') # 2 X 3 Matrix
81 | m2 = matrix('7 8 ; 9 10 ; 11 12') # 3 X 2 Matrix
82 |
83 | # In order to multiply, m1 column should be equal to m2 row that is 3
84 | # and result will be m1 row and m2 column that is 2 X 2
85 |
86 | # 1 2 3 7 8
87 | # 4 5 6 9 10
88 | # 11 12
89 |
90 | # result matrix will be 2 X 2 (m1 row will be multiplied with m2 column and so on)
91 |
92 | # 1*7+2*9+3*11 1*8+2*10+3*12
93 | # 4*7+5*9+6*11 4*8+5*10+6*12
94 |
95 | # 58 64
96 | # 139 154
97 |
98 | m3 = m1*m2
99 | print(m3)
100 | # [[ 58 64]
101 | # [139 154]]
102 |
--------------------------------------------------------------------------------
/27_function.py:
--------------------------------------------------------------------------------
1 |
2 | def addition(x, y):
3 | z = x + y
4 | return z
5 |
6 |
7 | result = addition(10, 12)
8 | print(result) # 22
9 |
10 |
11 | def add_sub(x, y):
12 | a = x + y
13 | s = x - y
14 | return a, s
15 |
16 |
17 | res, res1 = add_sub(10, 12)
18 | print(res) # 22
19 | print(res1) # -2
20 | print(res, res1) # 22 -2
21 |
--------------------------------------------------------------------------------
/28_functionarguments.py:
--------------------------------------------------------------------------------
1 |
2 | def updatevalue(value):
3 | print("Before updating value: ", value)
4 | print("Before updating value address: ", id(value))
5 | value = value * 2
6 | print("After updating value: ", value)
7 | print("After updating value address: ", id(value))
8 |
9 |
10 | inputValue = 5
11 | print("Initial inputValue: ", inputValue)
12 | print("Initial inputValue address: ", id(inputValue))
13 | updatevalue(inputValue)
14 | print("After updating inputValue: ", inputValue)
15 |
16 | # Initial inputValue: 5
17 | # Initial inputValue address: 140725372904360
18 | # Before updating value: 5
19 | # Before updating value address: 140725372904360
20 | # After updating value: 10
21 | # After updating value address: 140725372904520
22 | # After updating inputValue: 5
23 |
24 | # Input value is not getting changed even after calling function that means pass by value
25 |
26 |
27 | def updatelstvalue(value):
28 | print("Before updating value: ", value)
29 | print("Before updating value address: ", id(value))
30 | value[1] = 25
31 | print("After updating value: ", value)
32 | print("After updating value address: ", id(value))
33 |
34 |
35 | inputValue = [10, 20, 30]
36 | print("Initial inputValue: ", inputValue)
37 | print("Initial inputValue address: ", id(inputValue))
38 | updatelstvalue(inputValue)
39 | print("After updating inputValue: ", inputValue)
40 |
41 | # Initial inputValue: [10, 20, 30]
42 | # Initial inputValue address: 2798836798784
43 | # Before updating value: [10, 20, 30]
44 | # Before updating value address: 2798836798784
45 | # After updating value: [10, 25, 30]
46 | # After updating value address: 2798836798784
47 | # After updating inputValue: [10, 25, 30]
48 |
49 | # Input Value (List) is getting changed after calling function that means pass by reference
50 |
--------------------------------------------------------------------------------
/29_typesofarguments.py:
--------------------------------------------------------------------------------
1 |
2 | def addition(x, y): # formal arguments
3 | z = x + y
4 | print(z)
5 |
6 |
7 | addition(14, 10) # actual arguments (Position, Keyword, Default, Variable Length)
8 |
9 |
10 | def employee(name, age=18):
11 | print(name)
12 | print(age)
13 |
14 |
15 | # Position
16 | employee('Akshay', 42) # maintain position that is first name and then age
17 |
18 | # Keyword
19 | employee(age=42, name='Akshay')
20 |
21 | # Default
22 | employee('Akshay')
23 | employee('Akshay', 28)
24 |
25 |
26 | # Variable Length
27 | def add(x, *y): # * means multiple arguments
28 | z = x
29 | for i in y:
30 | z = z + i
31 | print(z) # 124
32 |
33 |
34 | add(14, 10, 19, 81)
35 |
36 |
37 | def person(name, **data): # ** means multiple arguments with arguments
38 | print(name)
39 | for i, j in data.items():
40 | print(i, j)
41 |
42 |
43 | person('Akshay', age=42, city='Hyderabad', mob=9898989898)
44 | # Akshay
45 | # age 42
46 | # city Hyderabad
47 | # mob 9898989898
48 |
--------------------------------------------------------------------------------
/2_power.py:
--------------------------------------------------------------------------------
1 |
2 | print(f'2 ** 3 = 8 [power] { 2 ** 3}')
3 |
--------------------------------------------------------------------------------
/30_globalandlocalvariable.py:
--------------------------------------------------------------------------------
1 |
2 | x = 14
3 |
4 |
5 | # Global variable - accessible inside function
6 | def accessvariable():
7 | print("Inside Function: ", x)
8 |
9 |
10 | accessvariable()
11 | print("Outside Function: ", x)
12 | # Inside Function: 14
13 | # Outside Function: 14
14 |
15 |
16 | # Global variable - change value of global variable creates actually new
17 | def accessvariable():
18 | x = 10
19 | print("Inside Function: ", x)
20 |
21 |
22 | accessvariable()
23 | print("Outside Function: ", x)
24 | # Inside Function: 10
25 | # Outside Function: 14
26 |
27 |
28 | # Global variable - change value of global variable without creating new
29 | def accessvariable():
30 | global x
31 | x = 10
32 | print("Inside Function: ", x)
33 |
34 |
35 | accessvariable()
36 | print("Outside Function: ", x)
37 | # Inside Function: 10
38 | # Outside Function: 10
39 |
40 |
41 | # Global variable - change value of global variable in presence of local variable with same name
42 | def accessvariable():
43 | x = 10
44 | globals()['x'] = 25
45 | print("Inside Function - local: ", x)
46 | print("Inside Function - global: ", globals()['x'])
47 |
48 |
49 | accessvariable()
50 | print("Outside Function: ", x)
51 | # Inside Function - local: 10
52 | # Inside Function - global: 25
53 | # Outside Function: 25
54 |
--------------------------------------------------------------------------------
/31_listasparameter.py:
--------------------------------------------------------------------------------
1 |
2 | def counter(lst):
3 | even = 0
4 | odd = 0
5 |
6 | for i in lst:
7 | if i % 2 == 0:
8 | even += 1
9 | else:
10 | odd += 1
11 |
12 | return even, odd
13 |
14 |
15 | numlst = [14, 10, 81, 17, 10, 17, 16, 11, 84]
16 | e, o = counter(numlst)
17 |
18 | print("Even : {} and Odd : {}".format(e, o))
19 | # Even : 5 and Odd : 4
20 |
--------------------------------------------------------------------------------
/32_recursion.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | print(sys.getrecursionlimit()) # 1000 this is the default limit
4 |
5 | sys.setrecursionlimit(2000)
6 | print(sys.getrecursionlimit()) # 2000 limit we increased to
7 |
8 |
9 | def factorial(n):
10 | if n == 0:
11 | return 1
12 | return n * factorial(n - 1)
13 |
14 |
15 | result = factorial(5)
16 | print(result) # 120
17 |
--------------------------------------------------------------------------------
/33_anonymousfunction.py:
--------------------------------------------------------------------------------
1 | from functools import reduce
2 |
3 |
4 | # Normal function
5 | def square(x):
6 | x = x * x
7 | return x
8 |
9 |
10 | result = square(5)
11 | print(result) # 25
12 |
13 | # Anonymous function
14 |
15 | fun = lambda x: x * x
16 | result = fun(6)
17 | print(result) # 36
18 |
19 | # filter
20 |
21 |
22 | def is_even(n):
23 | return n % 2 == 0
24 |
25 |
26 | nums = [14, 10, 81, 17, 10, 17, 16, 11, 84]
27 | evens = list(filter(is_even, nums))
28 | print(evens)
29 | # [14, 10, 10, 16, 84]
30 |
31 | odd = list(filter(lambda n: n % 2 != 0, nums))
32 | print(odd)
33 | # [81, 17, 17, 11]
34 |
35 |
36 | # map
37 |
38 | doubles = list(map(lambda n: n * 2, evens))
39 | print(doubles) # [28, 20, 20, 32, 168]
40 |
41 | # reduce
42 |
43 | total = reduce(lambda a, b: a + b, doubles)
44 | print(total) # 268
45 |
--------------------------------------------------------------------------------
/34_decorator.py:
--------------------------------------------------------------------------------
1 |
2 | # divide two numbers with condition that if numerator is less than denominator, swap the value
3 |
4 | def division(a, b):
5 | print(a / b)
6 |
7 |
8 | def swap_division(func): # decorator applies logic on existing function, so no need to modify existing function
9 | def inner(x, y):
10 | if x < y:
11 | x, y = y, x
12 | return func(x, y)
13 |
14 | return inner
15 |
16 |
17 | swapDivision = swap_division(division)
18 | swapDivision(4, 8) # 2.0 parameter value got swapped and result is 8 / 4 = 2.0
19 |
--------------------------------------------------------------------------------
/35_module.py:
--------------------------------------------------------------------------------
1 | from calc import *
2 |
3 | a = 14
4 | b = 10
5 | c = add(a, b)
6 | print(c)
7 |
8 |
9 |
--------------------------------------------------------------------------------
/36_specialvariable.py:
--------------------------------------------------------------------------------
1 |
2 | print(__name__) # __main__
3 |
4 |
5 | def main():
6 | print("Hello")
7 | print("Welcome User")
8 |
9 |
10 | if __name__ == "__main__":
11 | main()
12 |
--------------------------------------------------------------------------------
/37_classandobject.py:
--------------------------------------------------------------------------------
1 |
2 | class Pizza:
3 |
4 | def get_raw_material(self):
5 | print("dough, cheese, tomato, onion, olive")
6 |
7 |
8 | pizza1 = Pizza()
9 | pizza2 = Pizza()
10 |
11 | # Call class method and pass object as parameter
12 | Pizza.get_raw_material(pizza1)
13 | Pizza.get_raw_material(pizza2)
14 |
15 | # Call class method using an object where no need to pass object as parameter
16 | pizza1.get_raw_material()
17 | pizza2.get_raw_material()
18 |
--------------------------------------------------------------------------------
/38_initmethod.py:
--------------------------------------------------------------------------------
1 |
2 | class Mobile:
3 |
4 | def __init__(self, company, version):
5 | self.company = company
6 | self.version = version
7 |
8 | def get_mobile(self):
9 | print("My mobile :", self.company, self.version)
10 |
11 |
12 | mob1 = Mobile("Apple", 15)
13 | mob2 = Mobile("Samsung", 12)
14 |
15 | mob1.get_mobile()
16 | mob2.get_mobile()
17 |
18 | # My mobile : Apple 15
19 | # My mobile : Samsung 12
20 |
--------------------------------------------------------------------------------
/39_typesofvariables.py:
--------------------------------------------------------------------------------
1 | class Employee:
2 |
3 | type = "FullTime" # class level variable
4 |
5 | def __init__(self):
6 | self.company = "Apple" # instance level variable
7 | self.experience = 10 # instance level variable
8 |
9 |
10 | e1 = Employee()
11 | e2 = Employee()
12 |
13 | e2.experience = 5
14 |
15 | Employee.type = "PartTime" # change in class level variable implements in all instances
16 |
17 | print(e1.company, e1.experience, e1.type)
18 | print(e2.company, e2.experience, e2.type)
19 |
20 | # Apple 10 PartTime
21 | # Apple 5 PartTime
22 |
--------------------------------------------------------------------------------
/3_modulus.py:
--------------------------------------------------------------------------------
1 |
2 | print(f'10 % 3 = 1 [modulus] { 10 % 3}')
3 |
--------------------------------------------------------------------------------
/40_typesofmethods.py:
--------------------------------------------------------------------------------
1 |
2 | class Author:
3 |
4 | name = 'Akshay'
5 |
6 | def __init__(self, r1, r2, r3):
7 | self.r1 = r1
8 | self.r2 = r2
9 | self.r3 = r3
10 |
11 | def get_r1(self): # Accessor Method
12 | return self.r1
13 |
14 | def set_r1(self, value): # Mutator Method
15 | self.r1 = value
16 |
17 | def avg_rating(self): # Instance Method
18 | return (self.r1 + self.r2 + self.r3) / 3
19 |
20 | @classmethod
21 | def get_author(cls): # Class Method
22 | return cls.name
23 |
24 | @staticmethod # Static Method
25 | def get_class_info():
26 | print("This class provides Author and his rating info")
27 |
28 |
29 | a1 = Author(9, 8, 6)
30 | a2 = Author(8, 7, 6)
31 |
32 | print(a1.avg_rating())
33 | print(Author.get_author())
34 | Author.get_class_info()
35 |
--------------------------------------------------------------------------------
/41_innerclass.py:
--------------------------------------------------------------------------------
1 |
2 | class Customer:
3 |
4 | def __init__(self, name, id):
5 | self.name = name
6 | self.id = id
7 | self.add = self.Address()
8 |
9 | class Address:
10 |
11 | def __init__(self):
12 | self.add1 = 'Ayappa Colony'
13 | self.add2 = 'Besided Petrol Pump'
14 | self.city = 'Hyderabad'
15 |
16 |
17 | c1 = Customer('Jemin', 1)
18 | c2 = Customer('Chirantan', 2)
19 |
20 | a1 = c1.Address()
21 | print(a1.add1, a1.add2, a1.city)
22 |
23 | a2 = Customer.Address()
24 | print(a2.add1, a2.add2, a2.city)
25 |
--------------------------------------------------------------------------------
/42_singleinheritance.py:
--------------------------------------------------------------------------------
1 |
2 | class Parent:
3 | def parent_method1(self):
4 | print("Parent Method 1")
5 |
6 | def parent_method2(self):
7 | print("Parent Method 2")
8 |
9 |
10 | class Child(Parent):
11 | def child_method1(self):
12 | print("Child Method 1")
13 |
14 | def child_method2(self):
15 | print("Child Method 2")
16 |
17 |
18 | parent = Parent()
19 |
20 | parent.parent_method1()
21 | parent.parent_method2()
22 |
23 | # Parent Method 1
24 | # Parent Method 2
25 |
26 | child = Child()
27 |
28 | child.parent_method1()
29 | child.parent_method2()
30 | child.child_method1()
31 | child.child_method2()
32 |
33 | # Parent Method 1
34 | # Parent Method 2
35 | # Child Method 1
36 | # Child Method 2
37 |
--------------------------------------------------------------------------------
/43_multilevelinheritance.py:
--------------------------------------------------------------------------------
1 |
2 | class Parent:
3 | def parent_method1(self):
4 | print("Parent Method 1")
5 |
6 | def parent_method2(self):
7 | print("Parent Method 2")
8 |
9 |
10 | class Child(Parent):
11 | def child_method1(self):
12 | print("Child Method 1")
13 |
14 | def child_method2(self):
15 | print("Child Method 2")
16 |
17 |
18 | class GrandChild(Child):
19 | def grand_child_method1(self):
20 | print("Grand Child Method 1")
21 |
22 | def grand_child_method2(self):
23 | print("Grand Child Method 2")
24 |
25 |
26 | grandChild = GrandChild()
27 |
28 | grandChild.parent_method1()
29 | grandChild.parent_method2()
30 | grandChild.child_method1()
31 | grandChild.child_method2()
32 | grandChild.grand_child_method1()
33 | grandChild.grand_child_method2()
34 |
35 | # Parent Method 1
36 | # Parent Method 2
37 | # Child Method 1
38 | # Child Method 2
39 | # Grand Child Method 1
40 | # Grand Child Method 2
41 |
--------------------------------------------------------------------------------
/44_multipleinheritance.py:
--------------------------------------------------------------------------------
1 |
2 | class Parent:
3 | def parent_method1(self):
4 | print("Parent Method 1")
5 |
6 | def parent_method2(self):
7 | print("Parent Method 2")
8 |
9 |
10 | class Child:
11 | def child_method1(self):
12 | print("Child Method 1")
13 |
14 | def child_method2(self):
15 | print("Child Method 2")
16 |
17 |
18 | class GrandChild(Parent, Child):
19 | def grand_child_method1(self):
20 | print("Grand Child Method 1")
21 |
22 | def grand_child_method2(self):
23 | print("Grand Child Method 2")
24 |
25 |
26 | grandChild = GrandChild()
27 |
28 | grandChild.parent_method1()
29 | grandChild.parent_method2()
30 | grandChild.child_method1()
31 | grandChild.child_method2()
32 | grandChild.grand_child_method1()
33 | grandChild.grand_child_method2()
34 |
35 | # Parent Method 1
36 | # Parent Method 2
37 | # Child Method 1
38 | # Child Method 2
39 | # Grand Child Method 1
40 | # Grand Child Method 2
41 |
--------------------------------------------------------------------------------
/45_constructorininheritance.py:
--------------------------------------------------------------------------------
1 |
2 | class Parent:
3 | def __init__(self):
4 | print("Parent Constructor")
5 |
6 | def parent_method1(self):
7 | print("Parent Method 1")
8 |
9 |
10 | class Child(Parent):
11 | def child_method1(self):
12 | print("Child Method 1")
13 |
14 |
15 | child = Child() # Parent Constructor
16 | # when we create an instance of child, it calls parent constructor as child constructor is not available
17 |
18 |
19 | class Parent1:
20 | def __init__(self):
21 | print("Parent1 Constructor")
22 |
23 | def parent1_method1(self):
24 | print("Parent1 Method 1")
25 |
26 |
27 | class Child1(Parent1):
28 | def __init__(self):
29 | print("Child1 Constructor")
30 |
31 | def child1_method1(self):
32 | print("Child1 Method 1")
33 |
34 |
35 | child1 = Child1() # Child1 Constructor
36 | # when we create an instance of child1, it calls child1 constructor as child1 constructor is available
37 |
38 |
39 | class Parent2:
40 | def __init__(self):
41 | print("Parent2 Constructor")
42 |
43 | def parent2_method1(self):
44 | print("Parent2 Method 1")
45 |
46 |
47 | class Child2(Parent2):
48 | def __init__(self):
49 | super().__init__()
50 | print("Child2 Constructor")
51 |
52 | def child2_method1(self):
53 | print("Child2 Method 1")
54 |
55 |
56 | child2 = Child2()
57 | # Parent2 Constructor
58 | # Child2 Constructor
59 | # when we create an instance of child2, it calls Child2 constructor and using super it calls Parent2 constructor
60 |
61 |
62 | class Parent3:
63 | def __init__(self):
64 | print("Parent3 Constructor")
65 |
66 | def parent3_method1(self):
67 | print("Parent3 Method 1")
68 |
69 |
70 | class Child3:
71 | def __init__(self):
72 | super().__init__()
73 | print("Child3 Constructor")
74 |
75 | def child3_method1(self):
76 | print("Child3 Method 1")
77 |
78 |
79 | class GrandChild3(Parent3, Child3):
80 | def __init__(self):
81 | super().__init__()
82 | print("GrandChild3 Constructor")
83 |
84 | def grand_child3_method1(self):
85 | print("GrandChild3 Method 1")
86 |
87 |
88 | child3 = GrandChild3()
89 | # Parent3 Constructor
90 | # GrandChild3 Constructor
91 | # Super will give the priority to first inherited class (left to right), that's why Parent3 constructor is called in
92 | # multiple inheritance
93 |
--------------------------------------------------------------------------------
/46_polyducktyping.py:
--------------------------------------------------------------------------------
1 | class VegPizza:
2 |
3 | def prepare(self):
4 | print("Veg pizza prepared")
5 |
6 |
7 | class NonVegPizza:
8 |
9 | def prepare(self):
10 | print("Non Veg pizza prepared")
11 |
12 |
13 | class Pizza:
14 |
15 | def get_pizza(self, pizza_type):
16 | pizza_type.prepare()
17 |
18 |
19 | veg = VegPizza()
20 |
21 | pizza = Pizza()
22 | pizza.get_pizza(veg)
23 |
24 | # Veg pizza prepared - if you pass pizza_type as instance of NonVegPizza then it calls prepare method of NonVegPizza
25 |
--------------------------------------------------------------------------------
/47_polyoperatoroverloading.py:
--------------------------------------------------------------------------------
1 |
2 | class Employee:
3 |
4 | def __init__(self, s1, s2):
5 | self.s1 = s1
6 | self.s2 = s2
7 |
8 | def __add__(self, other):
9 | s1 = self.s1 + other.s1
10 | s2 = self.s2 + other.s2
11 | e3 = Employee(s1, s2)
12 |
13 | return e3
14 |
15 | def __gt__(self, other):
16 | s1 = self.s1 + other.s1
17 | s2 = self.s2 + other.s2
18 | if s1 > s2:
19 | return True
20 | else:
21 | return False
22 |
23 | def __str__(self):
24 | return '{} {}'.format(self.s1, self.s2)
25 |
26 |
27 | e1 = Employee(10, 20)
28 | e2 = Employee(30, 40)
29 |
30 | e3 = e1 + e2
31 | print(e3.s1) # 40
32 |
33 | if e1 > e2:
34 | print("e1 wins")
35 | else:
36 | print("e2 wins")
37 |
38 | # e2 wins
39 |
40 | print(e3) # 40 60 - by default it prints the address of an object but as we have overridden __str__ it prints value
41 |
--------------------------------------------------------------------------------
/48_methodoverloading.py:
--------------------------------------------------------------------------------
1 | class Student:
2 |
3 | def total_marks(self, maths=None, science=None, english=None):
4 | total = 0
5 | if maths!=None and science!=None and english!=None:
6 | total = maths+science+english
7 | elif maths!=None and science!=None:
8 | total = maths + science
9 | else:
10 | total = maths
11 |
12 | return total
13 |
14 |
15 | s = Student()
16 | print(s.total_marks(10, 20))
17 | print(s.total_marks(10, 20, 30))
18 |
--------------------------------------------------------------------------------
/49_methodoverriding.py:
--------------------------------------------------------------------------------
1 | class A:
2 |
3 | def display(self):
4 | print("display method of class A")
5 |
6 |
7 | class B(A):
8 | pass
9 |
10 |
11 | a1 = B()
12 | a1.display()
13 |
14 | # OUTPUT
15 | # display method of class A
16 |
17 |
18 | class C(A):
19 | def display(self):
20 | print("display method of class C")
21 |
22 |
23 | a1 = C()
24 | a1.display()
25 |
26 | # OUTPUT
27 | # display method of class C
28 |
--------------------------------------------------------------------------------
/4_printstring.py:
--------------------------------------------------------------------------------
1 |
2 | print('Akshay Patel')
3 | print('Akshay "Patel"')
4 | print("Akshay's Patel")
5 | print('"Akshay Patel"')
6 | print("'Akshay Patel'")
7 | print('Akshay\'s "Patel"')
8 | print(f'{10 * "Akshay"}')
9 | print(r'c:\docs\newfolder')
10 |
--------------------------------------------------------------------------------
/50_iterator.py:
--------------------------------------------------------------------------------
1 | class StarPattern:
2 |
3 | def __init__(self):
4 | self.str = "*"
5 |
6 | def __iter__(self):
7 | return self
8 |
9 | def __next__(self):
10 | if len(self.str) <= 5:
11 | val = self.str
12 | self.str = f'{(len(self.str)+1) * "*"}'
13 | return val
14 | else:
15 | raise StopIteration
16 |
17 |
18 | pattern = StarPattern()
19 |
20 | print(next(pattern))
21 |
22 | # *
23 | # **
24 | # ***
25 | # ****
26 | # *****
27 |
28 | for i in pattern:
29 | print(i)
30 |
31 | # It won't print again as values are read once
32 |
--------------------------------------------------------------------------------
/51_generator.py:
--------------------------------------------------------------------------------
1 | def starpattern():
2 | str = "*"
3 |
4 | while len(str) <= 5:
5 | val = str
6 | str = f'{(len(str)+1) * "*"}'
7 | yield val
8 |
9 |
10 | pattern = starpattern()
11 |
12 | for i in pattern:
13 | print(i)
14 |
15 | # *
16 | # **
17 | # ***
18 | # ****
19 | # *****
20 |
--------------------------------------------------------------------------------
/52_exceptionhandling.py:
--------------------------------------------------------------------------------
1 | # Errors
2 | # - Compile Time
3 | # - Logical
4 | # - Run Time
5 |
6 | x = 14
7 |
8 | try:
9 | y = int(input("Enter a number"))
10 | print("Resource Open")
11 | print(x / y)
12 |
13 | except ZeroDivisionError as e:
14 | print("You are dividing by zero", e)
15 |
16 | except ValueError as e:
17 | print("Invalid Input", e)
18 |
19 | except Exception as e:
20 | print("Something went wrong...")
21 |
22 | finally:
23 | print("Resource Closed")
24 |
--------------------------------------------------------------------------------
/53_multithreading.py:
--------------------------------------------------------------------------------
1 | from threading import *
2 | from time import sleep
3 |
4 |
5 | class Read(Thread):
6 | def run(self): # run is a method from thread class
7 | for i in range(5):
8 | print("Reading text")
9 | sleep(1) # Hold thread for one second to observe multiple threads are running
10 |
11 |
12 | class Write(Thread):
13 | def run(self):
14 | for i in range(5):
15 | print("Writing text")
16 | sleep(1)
17 |
18 |
19 | t1 = Read()
20 | t2 = Write()
21 |
22 | t1.start() # start is a method of thread class
23 | sleep(0.2) # hold for 2 millisecond to avoid collision
24 | t2.start()
25 |
26 | # join to wait for main thread to do his job, so "End" will be printed once both the threads job is done
27 | t1.join()
28 | t2.join()
29 |
30 | print("End") # executed on main thread
31 |
--------------------------------------------------------------------------------
/54_file.py:
--------------------------------------------------------------------------------
1 |
2 | # READ FILE
3 | f = open('introduction', 'r') # r represents read mode
4 |
5 | print(f)
6 | # <_io.TextIOWrapper name='introduction' mode='r' encoding='cp1252'>
7 |
8 | # Read first line of file
9 | print(f.readline(), end="")
10 |
11 | # Read first four character of line
12 | print(f.readline(4))
13 |
14 | # Read entire file
15 | print(f.read())
16 |
17 |
18 | # WRITE FILE
19 | f1 = open('introduction1', 'w') # w represents write mode | file will be created if it doesn't exist
20 | f1.write("Writing in file using python")
21 |
22 |
23 | # APPEND IN FILE
24 | f1 = open('introduction1', 'a') # a represents append
25 | f1.write("Further text appended")
26 |
27 |
28 | # COPY FILE CONTENT
29 | for data in f:
30 | f1.write(data)
31 |
32 | # READ IMAGE FILE
33 | f2 = open('me.jpg', 'rb') # rb represents read binary
34 | for data in f2:
35 | print(data)
36 |
37 | # COPY IMAGE FILE
38 | f3 = open('me1.JPG', 'wb') # wb represents write binary
39 | for data in f2:
40 | f3.write(data)
41 |
--------------------------------------------------------------------------------
/55_linearsearch.py:
--------------------------------------------------------------------------------
1 | pos = -1
2 |
3 |
4 | def search(lst, n):
5 | i = 0
6 |
7 | while i < len(list):
8 | if list[i] == n:
9 | globals()['pos'] = i
10 | return True
11 |
12 | i = i + 1
13 |
14 | return False
15 |
16 |
17 | lst = [5, 8, 4, 6, 9, 2]
18 | n = 9
19 |
20 |
21 | if search(lst, n):
22 | print("Value Found at ", pos+1)
23 | else:
24 | print("Value Not Found")
25 |
--------------------------------------------------------------------------------
/56_binarysearch.py:
--------------------------------------------------------------------------------
1 | '''
2 | BINARY SEARCH
3 |
4 | list = 4 7 8 12 45 99
5 | index = 0 1 2 3 4 5
6 |
7 | Search Value = 45
8 |
9 | STEP 1: Sort the list
10 | STEP 2: Find the lower and upper bound
11 | lower bound = first index i.e 0
12 | upper bound = last index i.e 5
13 | STEP 3: Find the mid-index
14 | mid-index = (lower + upper) / 2
15 | = (0 + 5) / 2
16 | = 2
17 | STEP 4: mid-value = 8
18 | STEP 5: If mid-value equals search value then end
19 | STEP 6: If search value is less than mid-value
20 | upper bound = mid-value
21 | STEP 7: If search value is greater than mid-value
22 | lower bound = mid-value
23 | lower bound = 8
24 | STEP 8: Repeat from step 3 till you get search value
25 | '''
26 |
27 | pos = -1
28 | def search(lst, n):
29 | lower_bound = 0
30 | upper_bound = len(lst)-1
31 |
32 | while lower_bound <= upper_bound:
33 | mid_value = (lower_bound + upper_bound) // 2
34 | if lst[mid_value] == n:
35 | globals()['pos'] = mid_value
36 | return True
37 | else:
38 | if lst[mid_value] < n:
39 | lower_bound = mid_value + 1
40 | else:
41 | upper_bound = mid_value - 1
42 |
43 | return False
44 |
45 |
46 | lst = [4, 7, 8, 12, 45, 99]
47 | n = 45
48 |
49 |
50 | if search(lst, n):
51 | print("Value Found at ", pos+1)
52 | else:
53 | print("Value Not Found")
54 |
--------------------------------------------------------------------------------
/57_bubblesort.py:
--------------------------------------------------------------------------------
1 | '''
2 | Bubble Sort
3 | STEP 1: Compare first value with second value
4 | if second value is smaller than first value
5 | then swap the value
6 | Do it till end of list
7 | STEP 2: Iterate step 1
8 | '''
9 |
10 |
11 | def sort(lst):
12 | for i in range(len(lst)-1, 0, -1): # start with last index till 0
13 | for j in range(i): # set range till last index
14 | if lst[j] > lst[j+1]:
15 | temp = lst[j]
16 | lst[j] = lst[j+1]
17 | lst[j+1] = temp
18 |
19 |
20 | lst = [5, 3, 8, 6, 7, 2]
21 | sort(lst)
22 |
23 | print(lst)
24 |
25 | # OUTPUT
26 | # [2, 3, 5, 6, 7, 8]
27 |
--------------------------------------------------------------------------------
/58_selectionsort.py:
--------------------------------------------------------------------------------
1 | '''
2 | SELECTION SORT
3 | STEP 1: Find the minimum value and set on 1st index
4 | STEP 2: Find again the minimum value and set on 2nd index and so on...
5 | '''
6 |
7 | def sort(lst):
8 | for i in range(5):
9 | minpos = i
10 | for j in range(i, 6):
11 | if lst[j] < lst[minpos]:
12 | minpos = j
13 |
14 | temp = lst[i]
15 | lst[i] = lst[minpos]
16 | lst[minpos] = temp
17 |
18 |
19 | lst = [5, 3, 8, 6, 7, 2]
20 | sort(lst)
21 |
22 | print(lst)
23 |
24 | # OUTPUT
25 | # [2, 3, 5, 6, 7, 8]
--------------------------------------------------------------------------------
/59_zipfunction.py:
--------------------------------------------------------------------------------
1 | fnames = ('Akshay', 'Chintan', 'Ashwin')
2 | lnames = ('Patel', 'Goswami', 'Fofandi')
3 |
4 | zipped = set(zip(fnames, lnames))
5 |
6 | print(zipped)
7 | # {('Akshay', 'Patel'), ('Chintan', 'Goswami'), ('Ashwin', 'Fofandi')}
8 |
9 | for (a, b) in zipped:
10 | print(a, b)
11 |
12 | # Akshay Patel
13 | # Chintan Goswami
14 | # Ashwin Fofandi
15 |
--------------------------------------------------------------------------------
/5_stringvariable.py:
--------------------------------------------------------------------------------
1 |
2 | name = 'akshay'
3 | print(name) # akshay
4 | print(name[0]) # a
5 | print(name[5]) # y
6 | print(name[-1]) # y
7 | print(name[-6]) # a
8 | print(name[0:3]) # aks
9 | print(name[1:4]) # ksh
10 | print(name[3:]) # hay
11 | print(name[:3]) # aks
12 | print(name[3:10]) # hay
13 | print('patel ' + name[0:10]) # patel akshay
14 | print(len(name)) # 6
15 |
--------------------------------------------------------------------------------
/60_insertionsort.py:
--------------------------------------------------------------------------------
1 | '''
2 | INSERTION SORT
3 |
4 | 5 3 8 6 7 2
5 | sorted Unsorted
6 |
7 | 5 3 8 6 7 2
8 | sorted Unsorted
9 | Iterate till value to the immediate left is lower than the value to sort
10 | If immediate left value is higher than change the position
11 |
12 | 3 5 8 6 7 2
13 |
14 | Pick 8 in another iteration and follow above steps
15 | '''
16 |
17 |
18 | def sort(lst):
19 | for i in range(1, len(lst)):
20 | value_to_sort = lst[i]
21 | while lst[i-1] > value_to_sort and i > 0:
22 | lst[i], lst[i-1] = lst[i-1], lst[i]
23 | i = i - 1
24 |
25 | return lst
26 |
27 |
28 | lst = [5, 3, 8, 6, 7, 2]
29 | sort(lst)
30 |
31 | print(lst)
32 |
33 | # OUTPUT
34 | # [2, 3, 5, 6, 7, 8]
35 |
--------------------------------------------------------------------------------
/61_mergesort.py:
--------------------------------------------------------------------------------
1 | '''
2 | MERGE SORT
3 |
4 | 5 3 8 6 7 2
5 | _____________________
6 | 5 3 8 6 7 2 # divide into sub arrays
7 | _________ _________
8 | 5 3 8 6 7 2
9 | _ _____ _ _____
10 | 5 3 8 6 7 2
11 | _ _ _ _ _ _
12 | 5 3 8 6 2 7 # sort and merge back
13 | _ _____ _ _____
14 | 3 5 8 2 6 7
15 | _________ _________
16 | 2 3 5 6 7 8
17 | _____________________
18 |
19 | '''
20 |
21 |
22 | def sort(lst):
23 | if len(lst) > 1:
24 |
25 | center = len(lst) // 2
26 | left = lst[:center]
27 | right = lst[center:]
28 |
29 | # Sort the two halves
30 | sort(left)
31 | sort(right)
32 |
33 | i = j = k = 0
34 |
35 | while i < len(left) and j < len(right):
36 | if left[i] < right[j]:
37 | lst[k] = left[i]
38 | i += 1
39 | else:
40 | lst[k] = right[j]
41 | j += 1
42 | k += 1
43 |
44 | while i < len(left):
45 | lst[k] = left[i]
46 | i += 1
47 | k += 1
48 |
49 | while j < len(right):
50 | lst[k] = right[j]
51 | j += 1
52 | k += 1
53 |
54 | return lst
55 |
56 |
57 | lst = [5, 3, 8, 6, 7, 2]
58 | sort(lst)
59 |
60 | print(lst)
61 |
62 | # OUTPUT
63 | # [2, 3, 5, 6, 7, 8]
64 |
--------------------------------------------------------------------------------
/62_stack.py:
--------------------------------------------------------------------------------
1 |
2 | def new_stack():
3 | stack = []
4 | return stack
5 |
6 |
7 | def is_empty(stack):
8 | return len(stack) == 0
9 |
10 |
11 | def push(stack, item):
12 | stack.append(item)
13 | print("pushed item: " + item)
14 |
15 |
16 | def pop(stack):
17 | if is_empty(stack):
18 | return "stack is empty"
19 |
20 | return stack.pop()
21 |
22 |
23 | stack = new_stack()
24 | push(stack, str(10))
25 | push(stack, str(20))
26 | push(stack, str(30))
27 | push(stack, str(40))
28 | push(stack, str(50))
29 |
30 | print("stack before pop: " + str(stack))
31 | print("popped item: " + pop(stack))
32 | print("stack after pop: " + str(stack))
33 |
34 | '''
35 | pushed item: 10
36 | pushed item: 20
37 | pushed item: 30
38 | pushed item: 40
39 | pushed item: 50
40 | stack before pop: ['10', '20', '30', '40', '50']
41 | popped item: 50
42 | stack after pop: ['10', '20', '30', '40']
43 | '''
--------------------------------------------------------------------------------
/63_readexceldata.py:
--------------------------------------------------------------------------------
1 | import openpyxl
2 |
3 | wb = openpyxl.load_workbook('test.xlsx')
4 |
5 | ws = wb.active
6 |
7 | print('Total Rows: '+str(ws.max_row)+'. Total Columns: '+str(ws.max_column))
8 |
9 | my_list = list()
10 | for value in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=ws.max_column, values_only=True):
11 | my_list.append(value)
12 |
13 | for i in my_list:
14 | print(i)
15 |
--------------------------------------------------------------------------------
/64_queue.py:
--------------------------------------------------------------------------------
1 | class Queue:
2 |
3 | def __init__(self):
4 | self.queue = []
5 |
6 | def enqueue(self, item):
7 | self.queue.append(item)
8 |
9 | def dequeue(self):
10 | if len(self.queue) < 1:
11 | return None
12 | return self.queue.pop(0)
13 |
14 | def display(self):
15 | print("Queue Elements:", self.queue)
16 |
17 | def size(self):
18 | return len(self.queue)
19 |
20 |
21 | q = Queue()
22 | q.enqueue(10)
23 | q.enqueue(20)
24 | q.enqueue(30)
25 | q.enqueue(40)
26 | q.enqueue(50)
27 |
28 | q.display()
29 |
30 | print("Size of Queue:", q.size())
31 |
32 | print("First element removed:", q.dequeue())
33 |
34 | q.display()
35 |
--------------------------------------------------------------------------------
/65_dequeue.py:
--------------------------------------------------------------------------------
1 | class Deque:
2 | def __init__(self):
3 | self.items = []
4 |
5 | def is_empty(self):
6 | return self.items == []
7 |
8 | def add_rear(self, item):
9 | self.items.append(item)
10 |
11 | def add_front(self, item):
12 | self.items.insert(0, item)
13 |
14 | def remove_front(self):
15 | return self.items.pop(0)
16 |
17 | def remove_rear(self):
18 | return self.items.pop()
19 |
20 | def size(self):
21 | return len(self.items)
22 |
23 |
24 | d = Deque()
25 | print("Is Empty:", d.is_empty())
26 | print("Add Rear 10", d.add_rear(10))
27 | print("Add Rear 20", d.add_rear(20))
28 | print("Add Front 5", d.add_front(5))
29 | print("Add Front 1", d.add_front(1))
30 | print("Size:", d.size())
31 | print("Is Empty:", d.is_empty())
32 | print("Add Rear 30", d.add_rear(30))
33 | print("Items:", d.items)
34 | print("Remove Rear", d.remove_rear())
35 | print("Remove Front", d.remove_front())
36 | print("Add Front 2", d.add_front(2))
37 | print("Add rear 40", d.add_rear(40))
38 | print(d.items)
39 |
--------------------------------------------------------------------------------
/66_loadjsonstring.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | point = json.loads('{"x":10,"y":10}')
4 | print(point)
5 |
6 |
7 | print("x = {}".format(point.get("x")))
8 | print("y = {}".format(point.get("y")))
9 |
10 | # {'x': 10, 'y': 10}
11 | # x = 10
12 | # y = 10
13 |
--------------------------------------------------------------------------------
/67_loadjsonfile.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | path = "point1.json"
4 |
5 | point = json.load(open(path, mode='r'))
6 | print(point)
7 |
8 | print("x = {}".format(point.get("x")))
9 | print("y = {}".format(point.get("y")))
10 |
--------------------------------------------------------------------------------
/68_dumpjsonasstring.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | point = {
4 | "x": 50,
5 | "y": 50
6 | }
7 |
8 | point = json.dumps(point)
9 | print(point)
10 |
--------------------------------------------------------------------------------
/69_dumpjsonasjsonfile.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | point = {
4 | "x":100,
5 | "y":100
6 | }
7 |
8 |
9 | json.dump(point,open("./point2.json",mode='w'))
10 |
--------------------------------------------------------------------------------
/6_lists.py:
--------------------------------------------------------------------------------
1 |
2 | nums = [10, 20, 30, 40, 50, 60]
3 | print(nums) # [10, 20, 30, 40, 50, 60]
4 | print(nums[0]) # 10
5 | print(nums[5]) # 60
6 | print(nums[-1]) # 60
7 | print(nums[-6]) # 10
8 | print(nums[0:3]) # [10, 20, 30]
9 | print(nums[1:4]) # [20, 30, 40]
10 | print(nums[3:]) # [40, 50, 60]
11 | print(nums[:3]) # [10, 20, 30]
12 | print(nums[3:10]) # [40, 50, 60]
13 | print(len(nums)) # 6
14 |
15 | names = ['akshay', 'kumar', 'satish', 'chandra', 'patel']
16 | print(names) # ['akshay', 'kumar', 'satish', 'chandra', 'patel']
17 |
18 | values = [56.77, 'akshay', 5677]
19 | print(values) # [56.77, 'akshay', 5677]
20 |
21 | listoflist = [nums, names]
22 | print(listoflist) # [[10, 20, 30, 40, 50, 60], ['akshay', 'kumar', 'satish', 'chandra', 'patel']]
23 |
24 | nums.append(70)
25 | print(nums) # [10, 20, 30, 40, 50, 60, 70]
26 |
27 | nums.insert(2, 25)
28 | print(nums) # [10, 20, 25, 30, 40, 50, 60, 70]
29 |
30 | nums.remove(25)
31 | print(nums) # [10, 20, 30, 40, 50, 60, 70]
32 |
33 | nums.pop(2)
34 | print(nums) # [10, 20, 40, 50, 60, 70]
35 |
36 | nums.pop()
37 | print(nums) # [10, 20, 40, 50, 60]
38 |
39 | del nums[2:]
40 | print(nums) # [10, 20]
41 |
42 | nums.extend([30, 40, 50, 60])
43 | print(nums) # [10, 20, 30, 40, 50, 60]
44 |
45 | print(min(nums)) # 100
46 | print(max(nums)) # 60
47 | print(sum(nums)) # 210
48 |
49 | nums.sort()
50 | print(nums) # [10, 20, 30, 40, 50, 60]
51 |
--------------------------------------------------------------------------------
/70_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What's the expected output of the following code?
2 |
3 | a = 5
4 | # a = a + a
5 | print(a)
6 |
7 | # Output
8 | # 5
9 |
10 | # Hint
11 | # The a = a + a part of code is commented, and the interpreter ignores this line.
12 |
--------------------------------------------------------------------------------
/71_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What's the expected output of the following code?
2 |
3 | a = 1 # + 5
4 | a = a + a
5 | # a = a + 1
6 | print(a)
7 |
8 | # Output
9 | # 2
10 |
11 | # Hint
12 | # The interpreter ignores the code lines preceded by the # symbol.
13 |
--------------------------------------------------------------------------------
/72_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What's the expected output of the following code?
2 |
3 | planets = 1 + 1 // 2 * 3
4 | if planets > 0:
5 | print("#")
6 | elif planets > 1:
7 | print("##")
8 | else:
9 | print("###")
10 |
11 | # Output
12 | # #
13 |
14 | # Hint
15 | # Hence the expression 1 + 1 // 2 * 3 evaluates to 1, and the control reaches the very first print() invocation.
16 |
--------------------------------------------------------------------------------
/73_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What's the expected output of the following code?
2 |
3 | planets = 4 - 3 // 2 + -1
4 | if planets < 0:
5 | print("#")
6 | elif planets >= 2:
7 | print("##")
8 | else:
9 | print("###")
10 |
11 | # Output
12 | # ##
13 |
14 | # Hint
15 | # Hence the expression 4 - 3 // 2 + -1 evaluates to 2, and the control reaches to second print() invocation only.
16 |
--------------------------------------------------------------------------------
/74_codingquestion.py:
--------------------------------------------------------------------------------
1 | # How many asterisks (*) does the code output to the screen?
2 |
3 | torque = 5
4 | while torque > 0:
5 | torque -= 3
6 | print("*", end="")
7 | else:
8 | print("*")
9 |
10 | '''
11 | To find the answer, we need to analyze the sequence of values the torque variable takes:
12 | it starts with 5 and goes through 2 and -1. This means that the while loop's body is responsible for the first
13 | two asterisks. The third asterisk comes from the else: branch.
14 | '''
15 |
16 | # OUTPUT
17 | # ***
18 |
--------------------------------------------------------------------------------
/75_codingquestion.py:
--------------------------------------------------------------------------------
1 | # How many asterisks (*) does the code output to the screen?
2 |
3 | torque = 1
4 | while torque < 2:
5 | torque *= 2
6 | print("*", end="")
7 | else:
8 | print("*")
9 |
10 | '''
11 | The while loop's body is executed only once, as the torque variable is set
12 | to 2 during the loop's first turn. This means that the loop will emit one asterisk.
13 | The second asterisk is emitted by the else: branch.
14 | '''
15 |
16 | # OUTPUT
17 | # **
18 |
--------------------------------------------------------------------------------
/76_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What happens when the user runs the following code?
2 |
3 | power = 1
4 | while power != 10:
5 | power *= 2
6 | if power == 5:
7 | continue
8 | print("@", end="")
9 | else:
10 | print("@")
11 |
12 | '''
13 | As you can see, the power variable takes values which are subsequent power of 2(1,2,4,8,16,etc.)
14 | 10 does not belong to this set and the continue statement does not change anything either.
15 | Consequently, the loop has no chance to be terminated, and runs infinitely.
16 | '''
17 |
18 | # OUTPUT
19 | # The program enters an infinite loop
20 |
--------------------------------------------------------------------------------
/77_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What happens when the user runs the following code?
2 |
3 | power = 1
4 | while power < 5:
5 | power += 1
6 | print("@", end="")
7 | if power == 3:
8 | break
9 | else:
10 | print("@")
11 |
12 | '''
13 | As the power variable begins its life with the value 1, the control smoothly enters
14 | the while loop. Next, the power variable is incremented(it's 2 at the moment) and one @ is
15 | emitted. The loop's second turn causes the variable to be incremented again, and this is the moment
16 | when the break instruction goes onto the stage - the loop is terminated and the else: branch is executed.
17 | In effect, the second (and at the same time the last)@ is printed.
18 | '''
19 |
20 | # OUTPUT
21 | # @@
22 |
--------------------------------------------------------------------------------
/78_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What happens when the user runs the following code?
2 |
3 | angle = 0
4 | for i in range(5):
5 | if i % 2 == 1:
6 | angle += 1
7 | else:
8 | angle -= 1
9 | print(angle)
10 |
11 | '''
12 | A close look at the inside of the for loop's body shows that the angle variable is incremented
13 | twice; when the i variable is either 1 or 3 (these are the two cases when i % 2 == 1 is true).
14 | The decrement occurs once - inside the else: branch.
15 | That's why the final variable value is 1.
16 | '''
17 |
18 | # OUTPUT
19 | # 1
--------------------------------------------------------------------------------
/79_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What happens when the user runs the following code?
2 |
3 | angle = 1
4 | for i in range(2, 5):
5 | if 2 * i > 4:
6 | angle += 1
7 | else:
8 | angle -= 1
9 | print(angle)
10 |
11 | '''
12 | In the sequence 2, 3, 4 which is passed through by the i variable,
13 | only the first value (2) doesn't satisfy the condition 2 * i > 4.
14 | In effect, the angle variable is incremented twice inside the loop's body
15 | and decremented once inside the else: branch, which finally sets it to 2.
16 | '''
17 |
18 | # OUTPUT
19 | # 2
--------------------------------------------------------------------------------
/7_tuple.py:
--------------------------------------------------------------------------------
1 |
2 | # tuple
3 | tup = (10, 20, 30, 40, 50, 60)
4 | print(tup) # (10, 20, 30, 40, 50, 60)
5 | print(tup[1]) # 20
6 | # tup[1] = 25 # tuple value can not be changed
7 |
8 | # set - unique values | index not supported
9 | s = {10, 20, 30, 30, 20, 10}
10 | print(s) # {10, 20, 30}
11 | s.add(40)
12 | print(s) # {40, 10, 20, 30}
13 |
--------------------------------------------------------------------------------
/80_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected output of the following code?
2 |
3 | others = 0
4 | for i in range(2):
5 | for j in range(2):
6 | if i != j:
7 | others += 1
8 | else:
9 | others += 1
10 | print(others)
11 |
12 | '''
13 | Both loops, the outer and the inner, go through the same, two-element set of values
14 | which consist of 0 and 1. This means the condition i != j will be satisfied twice, which
15 | results in two increments performed inside the loop's body and an additional one in the outer
16 | loop's else: branch, that's why the final others value is equal to 3.
17 | '''
18 |
19 | # OUTPUT
20 | # 3
21 |
--------------------------------------------------------------------------------
/81_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected output of the following code?
2 |
3 | others = -1
4 | for i in range(1, 3):
5 | for j in range(1, 2):
6 | if i == j:
7 | others += 1
8 | else:
9 | others += 1
10 | print(others)
11 |
12 | '''
13 | The sequence of values produced by the outer for loop contains two values: 1 and 2.
14 | The inner for loop covers one value only:1. A common part of these two sets contains
15 | only one value: 1. So the other variable is incremented once the inner loop's body
16 | and twice inside the loop's else: branch. Considering that the initial variable's value
17 | is -1, it will leave the loops with 2.
18 | '''
19 |
20 | # OUTPUT
21 | # 2
22 |
--------------------------------------------------------------------------------
/82_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected output of the following code?
2 |
3 | list_one = [1, 2]
4 | list_two = list_one[:]
5 | list_two.append(3)
6 | print(list_one[-1])
7 |
8 | '''
9 | As list_two originates from a slice of list_one, both these names refer to
10 | different(separate) data. Therefore, the element appended to the first of them
11 | doesn't exist in the second, and vice versa.
12 | '''
13 |
14 | # OUTPUT
15 | # 2
16 |
--------------------------------------------------------------------------------
/83_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | answers = (True, True, False)
4 | selection = answers[3:]
5 | points = 0
6 | for answer in selection[-2:]:
7 | if answer:
8 | points += 1
9 | print(points)
10 |
11 | '''
12 | The selection has been created as a zero-element of answers
13 | (the slice starts beyond the list!). The second slice (the
14 | one in the loop statement) changes nothing (the empty list
15 | remains empty), and therefore points is not incremented even
16 | once inside the loop, and its final value is 0.
17 | '''
18 |
19 | # OUTPUT
20 | # 0
21 |
--------------------------------------------------------------------------------
/84_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | answers = (True, False, True)
4 | selection = answers[2:]
5 | points = 0
6 | for answer in selection[-1:]:
7 | if answer:
8 | points += 1
9 | print(points)
10 |
11 | '''
12 | The selection has been created as a one-element slice of the answers
13 | list. Therefore, it is a separate, one-element list which contains True.
14 | The second slice (the one in the loop statement) changes nothing(the only
15 | list element is also its last element). In effect, points is incremented
16 | once inside the loop and its final value is 1.
17 | '''
18 |
19 | # OUTPUT
20 | # 1
21 |
--------------------------------------------------------------------------------
/85_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected output of the following code?
2 |
3 | train_speed = {"FlyingScotman": 201, "TGV": 320, "Shinkansen": 320}
4 |
5 | for train in train_speed:
6 | print(train[0], end="")
7 |
8 | '''
9 | Iterating through a dictionary is actually iterating through a list of all the dictionary's keys.
10 | The [0] index retrieves the first character of each key so we won't expect any other answer.
11 | '''
12 |
13 | # OUTPUT
14 | # FTS
15 |
--------------------------------------------------------------------------------
/86_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected output of the following code?
2 |
3 | train_speed = {"FlyingScotman": 201, "TGV": 320, "Shinkansen": 320}
4 |
5 | for train in train_speed.values():
6 | print(str(train)[0], end="")
7 |
8 | '''
9 | As the .values() method returns a list of dictionary values(the keys are ignored!), the [0] index
10 | retrieves the first character of the string obtained from each value's integer number. This is where
11 | the answer came from.
12 | '''
13 |
14 | # OUTPUT
15 | # 233
16 |
--------------------------------------------------------------------------------
/87_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def sample(value):
4 | return value + value
5 |
6 |
7 | x = sample(value=1)
8 | y = sample(x)
9 | print(y)
10 |
11 |
12 | '''
13 | The function returns its argument doubled. Although each of the invocations makes use of
14 | different argument passing techniques, the effect remains the same and this is why the
15 | initial argument value equal to 1 turns into 4.
16 | '''
17 |
18 | # OUTPUT
19 | # 4
--------------------------------------------------------------------------------
/88_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def process(data):
4 | data = [1, 2, 3]
5 | return data[-2]
6 |
7 |
8 | measurements = [0 for i in range(3)]
9 | process(measurements)
10 | print(measurements[-2])
11 |
12 |
13 | '''
14 | The process() function redefines its parameter, which means that the parameter visible
15 | locally (in the function's scope) refers to different data than the argument used globally.
16 | It also means that this change doesn't affect global data.
17 | Therefore the measurements list still contains zeros.
18 | '''
19 |
20 | # OUTPUT
21 | # 0
22 |
--------------------------------------------------------------------------------
/89_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def process(data):
4 | data[1] = 2
5 | return data[-2]
6 |
7 |
8 | measurements = [0 for i in range(3)]
9 | process(measurements)
10 | print(measurements[-2])
11 |
12 |
13 | '''
14 | The process() function redefines the second element of its parameter which means that
15 | the change affects the argument(which is visible globally). This is why the middle element of
16 | the measurements list(which can be indexed as [-2]) contains 2, not zero.
17 | '''
18 |
19 | # OUTPUT
20 | # 2
21 |
--------------------------------------------------------------------------------
/8_dictionary.py:
--------------------------------------------------------------------------------
1 |
2 | # dictionary
3 |
4 | data = {1: 'akshay', 2: 'kumar', 4: 'patel'}
5 | print(data) # {1: 'akshay', 2: 'kumar', 4: 'patel'}
6 | print(data[4]) # patel
7 | # print(data[3]) - throws an error
8 | print(data.get(1)) # akshay
9 | print(data.get(3)) # None
10 | print(data.get(3, 'Not Found')) # Not Found
11 |
12 | # merge two list and convert into dictionary
13 | keys = ['akshay', 'mansi', 'panth']
14 | values = ['SevUsal', 'VadaPav', 'ColdCoco']
15 | dic = dict(zip(keys, values))
16 | print(dic) # {'akshay': 'SevUsal', 'mansi': 'VadaPav', 'panth': 'ColdCoco'}
17 |
18 | dic['Kush'] = 'IceCream'
19 | print(dic) # {'akshay': 'SevUsal', 'mansi': 'VadaPav', 'panth': 'ColdCoco', 'Kush': 'IceCream'}
20 |
21 | del dic['Kush']
22 | print(dic) # {'akshay': 'SevUsal', 'mansi': 'VadaPav', 'panth': 'ColdCoco'}
23 |
24 | # dictionary contains values, list and dictionary
25 | prog = {'ssp': 'Akshay', 'dup': ['Jay', 'Anjali'], 'ump': {'elder': 'Sunil', 'younger': 'Dinesh'}}
26 | print(prog) # {'ssp': 'Akshay', 'dup': ['Jay', 'Anjali'], 'ump': {'elder': 'Sunil', 'younger': 'Dinesh'}}
27 | print(prog['ssp']) # Akshay
28 | print(prog['dup'][1]) # Anjali
29 | print(prog['ump']['younger']) # Dinesh
30 |
--------------------------------------------------------------------------------
/90_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def combine(width, height=10, depth=0, is_3D=False):
4 | return (is_3D, width, height, depth)
5 |
6 |
7 | print(combine(height=1, width=2)[3])
8 |
9 |
10 | '''
11 | Two parameters are set during invocation i.e. height=1 and width=2
12 | two parameters retains their default values i.e depth=0 and is_3D=False
13 | In effect, the function returns the following list: [False, 2, 1, 0]
14 | the list's fourth element is zero, thus, you see it on the screen.
15 | '''
16 |
17 | # OUTPUT
18 | # 0
19 |
--------------------------------------------------------------------------------
/91_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def combine(width, height=2, depth=0, is_3D=False):
4 | return (is_3D, width, height, depth)
5 |
6 |
7 | print(combine(1)[2])
8 |
9 |
10 | '''
11 | Only one parameter is explicitly set during invocation and it's width
12 | all remaining parameters retain their default values
13 | consequently, the function returns the following tuple: [False, 1, 2, 0]
14 | the tuple's third element is 2and this is the output that goes to the screen.
15 | '''
16 |
17 | # OUTPUT
18 | # 2
19 |
--------------------------------------------------------------------------------
/92_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def walk(stop, start=1):
4 | print(start, end=" ")
5 | if start + 1 < stop:
6 | walk(stop, start + 1)
7 |
8 |
9 | walk(3)
10 |
11 |
12 | '''
13 | walk(3) which is in fact executed as walk(3, 1)
14 | walk(3, 2) (1 is printed in this cycle)
15 | No invocation occurs now as the condition is not met, but 2 is printed)
16 | '''
17 |
18 | # OUTPUT
19 | # 1 2
20 |
--------------------------------------------------------------------------------
/93_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | def walk(top):
4 | if top == 0:
5 | return 0
6 | return top + walk(top - 1)
7 |
8 |
9 | print(walk(2))
10 |
11 |
12 | '''
13 | walk(2) which returns 2 + walk(1)
14 | walk(1) which returns 1 + walk(0)
15 | walk(0) which returns 0 and breaks the invocation chain
16 | consequently, the final result is 2 + 1 + 0
17 | '''
18 |
19 | # OUTPUT
20 | # 3
21 |
--------------------------------------------------------------------------------
/94_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | a = True
4 | print(('A', 'B')[a == False])
5 |
6 | '''
7 | Here ('A', 'B') is a tuple. We could access values in tuple, use the square brackets []. The a == False
8 | is an expression that could be evaluated as boolean. In Python 3.x True and False are keywords and will
9 | always be equal to 1 and 0. So the result will be A
10 | '''
11 |
12 |
13 | # OUTPUT
14 | # A
15 |
--------------------------------------------------------------------------------
/95_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | lst = ['a', 'b', 'c', 'd', 'e']
4 | print(lst[10:])
5 |
6 | # The above code will output [], and will not result in an IndexError.
7 |
8 | # OUTPUT
9 | # []
10 |
--------------------------------------------------------------------------------
/96_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | squares = []
4 |
5 | for x in range(5):
6 | squares.append(lambda: x**2)
7 |
8 | print(squares[2]())
9 | print(squares[4]())
10 |
11 | '''
12 | This happens because x is not local to the lambdas, but is defined in the outer scope,
13 | and it is accessed when the lambda is called — not when it is defined.
14 | At the end of the loop, the value of x is 4, so all the functions now return 4**2, i.e. 16.
15 | '''
16 |
17 |
18 | # OUTPUT
19 | # 16
20 | # 16
21 |
--------------------------------------------------------------------------------
/97_codingquestion.py:
--------------------------------------------------------------------------------
1 | # What is the expected result of the following code?
2 |
3 | x = 100
4 | y = x
5 | x = 200
6 |
7 | print(y)
8 |
9 | '''
10 | Python does not read this as, “y should now refer to the variable x.” Rather, it read it as,
11 | “y should now refer to whatever value x refers to.”
12 | Because x refers to the integer 100, y now refers to the integer 100.
13 | After these two assignments (“x = 100” and “y = x”), there are now two references to the integer 100
14 | that did not previously exist.
15 | When we say that “x = 200”, we’re removing one of those references, such that x no longer refers to 100.
16 | Instead, x will now refer to the integer 200.
17 | '''
18 |
19 | # OUTPUT
20 | # 100
21 |
--------------------------------------------------------------------------------
/98_codingquestion.py:
--------------------------------------------------------------------------------
1 | # Is this valid in python?
2 |
3 | def my_function():
4 | print(my_function.what)
5 |
6 |
7 | my_function.what = "right?"
8 | my_function()
9 |
10 |
11 | '''
12 | It is valid. In Python, everything is an object, including functions.
13 | But if we don't have what defined, we will get an Attribute error.
14 | '''
15 |
16 | # OUTPUT
17 | # right?
18 |
--------------------------------------------------------------------------------
/99_codingquestion.py:
--------------------------------------------------------------------------------
1 | # Check if string is a palindrome?
2 |
3 | n = input("enter string:")
4 | result = str(n) == str(n)[::-1]
5 |
6 | print(result)
7 |
8 | '''
9 | We're checking if the string representation of n equals the inverted string representation of n
10 | The [::-1] slice takes care of inverting the string
11 | After that, we compare for equality using ==
12 | '''
--------------------------------------------------------------------------------
/9_memoryaddofvariable.py:
--------------------------------------------------------------------------------
1 |
2 | num = 5677 # variable with value
3 | id(num) # get memory address of variable
4 | print(id(num))
5 |
6 | name = 'akshay'
7 | id(name)
8 | print(id(name))
9 |
10 | # declare two variables, assign value of one into another, check memory address
11 | a = 1410
12 | b = a
13 | print(id(a))
14 | print(id(b))
15 | # both variables memory address is same
16 |
17 | # declare one more variable with value 1410, check memory address
18 | c = 1410
19 | print(id(c))
20 | # memory address is same as a and b that means memory address is assigned to value and not the variable
21 |
--------------------------------------------------------------------------------
/calc.py:
--------------------------------------------------------------------------------
1 |
2 | def add(x, y):
3 | return x + y
4 |
5 |
6 | def sub(x, y):
7 | return x - y
8 |
9 |
10 | def multi(x, y):
11 | return x * y
12 |
13 |
14 | def div(x, y):
15 | return x / y
16 |
--------------------------------------------------------------------------------
/introduction:
--------------------------------------------------------------------------------
1 | Hello, I am Akshaykumar Patel
2 | I am having 15+ years of experience in web development
3 | I have started learning python
--------------------------------------------------------------------------------
/introduction1:
--------------------------------------------------------------------------------
1 | Writing in file using pythonFurther text appended
--------------------------------------------------------------------------------
/me.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshayblevel/Python-Beginner/80fedbc87b847096ecce44a44f3b5924bedfd485/me.jpg
--------------------------------------------------------------------------------
/me1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshayblevel/Python-Beginner/80fedbc87b847096ecce44a44f3b5924bedfd485/me1.jpg
--------------------------------------------------------------------------------
/point1.json:
--------------------------------------------------------------------------------
1 | {
2 | "x":5,
3 | "y":5
4 | }
--------------------------------------------------------------------------------
/test.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshayblevel/Python-Beginner/80fedbc87b847096ecce44a44f3b5924bedfd485/test.xlsx
--------------------------------------------------------------------------------