0% found this document useful (0 votes)
5 views2 pages

Printing Techniques and Python Basics

k

Uploaded by

adityakhouri2001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Printing Techniques and Python Basics

k

Uploaded by

adityakhouri2001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Currently we are learning printing

In [1]: print('Techno India University is the best college in West Bengal')

Techno India University is the best college in West Bengal

Number of Style of writing headings

Heading-1
Heading-2
Heading-3
Heading-4
Heading-5
Heading-6

Heading-1
Heading-2
Heading-3
Heading-4
Heading-5
Heading-6

Manish Iam a good learner

Gajendra Is a good student

In [2]: # This is a comment


# This is another comment
print("TIU is the best college")

TIU is the best college

In [3]: '''
This is a multi line comment

'''

'\nThis is a multi line comment\n\n'


Out[3]:

Input Output
In [93]: num1 = input("Please enter the first number: ")
num2 = input("Please enter the second number: ")
print (num1, type(num1), num2, type(num2))
result = num1 + num2
print ("So the result is", result)
print ("End of the program...")

Please enter the first number: 10


Please enter the second number: 20
10 <class 'str'> 20 <class 'str'>
So the result is 1020
End of the program...

In [5]: num1 = int(input("Please enter the first number: "))


num2 = int(input("Please enter the second number: "))
print (num1, type(num1), num2, type(num2))
result = num1 + num2
print ("So the result is", result)
print ("End of the program...")

Please enter the first number: 10


Please enter the second number: 20
10 <class 'int'> 20 <class 'int'>
So the result is 30
End of the program...

In [6]: num1 = int(input("Please enter the first number: "))


num2 = int(input("Please enter the second number: "))
result = num1 + num2
print (num1, type(num1), num2, type(num2))

Please enter the first number: 10


Please enter the second number: 20
10 <class 'int'> 20 <class 'int'>

Printing Techniques
In [7]: print ("So the sum of", num1, "+", num2, "=", result)
print ("So the sum of " + str(num1) + " + " + str(num2) + " = " + str(result))
print ("So the sum of {} + {} = {}".format(num1, num2, result)) # {} denotes place holder
print ("So the sum of {0} + {1} = {2}".format(num1, num2, result)) # numbered place holder
print ("So the sum of {2} + {0} = {1}".format(num2, result, num1))
print ("So the sum of {fnum} + {snum} = {tot}".format(fnum = num1, snum = num2, tot = result)) # labeled plac
print ("So the sum of {fnum} + {snum} = {tot}".format(snum = num2, fnum = num1, tot = result))
print ("So the sum of %d + %d = %d"%(num1, num2, result))
print ("So the sum of %d + %f = %d"%(num1, num2, result))
print ("So the sum of %d + %4.2f = %d"%(num1, num2, result))
print (f"So the sum of {num1} + {num2} = {result}") # smart formatting

So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20 = 30
So the sum of 10 + 20.000000 = 30
So the sum of 10 + 20.00 = 30
So the sum of 10 + 20 = 30

In [8]: result = eval(input("Please enter your expression: "))


print (result)

Please enter your expression: (10+(20*2))


50

Operators
In [9]: # Arithmetic operators: + - * / // ** %
print (100 + 40) # addition
print (100 - 40) # subtraction
print (100 * 40) # multiplication
print (100 / 40) # float division
print (100 // 40) # integer division
print (100 ** 4) # exponentiation, a to the power of b
print (100 % 40) # modulus, remainder of the division

140
60
4000
2.5
2
100000000
20

In [10]: # logical operators: and or not


print (True and True, True and False, False and True, False and False) # True, False, None keywords starts wi
print (True or True, True or False, False or True, False or False)
print (not True, not False)

True False False False


True True True False
False True

In [11]: # Relational operators: > >= < <= != == -gt -ge -lt -le -ne -eq, .gt. .ge. .lt. .le. .ne. .eq
print (100 > 50, 100 >= 100, 100 < 400, 100 <= 500, 100 != 200, 400 == 400)

True True True True True True

In [12]: # Ternary operator:


# Operator classifications: Unary (one operand), Binary (two operands) and Ternary (three operands)
# Unary: +10 -20, Binary: 10 + 20, 30 * 4, Ternary: as shown below (True part, Condition and False part)
num1 = 100
result = "EVEN Number" if (num1 % 2 == 0) else "ODD Number" # result = num1 % 2? "True": "False" (in C, C+
print (result)
num1 = 101
result = "EVEN Number" if (num1 % 2 == 0) else "ODD Number"
print (result)

EVEN Number
ODD Number

In [13]: # Assignment and special assignment operators: = += -= /= //= *= **= %=


num1 = 100
print (num1)
num1 += 10
print (num1)
num1 -= 10
print (num1)
num1 *= 10
print (num1)
num1 **= 2
print (num1)

100
110
100
1000
1000000

In [14]: # Bitwise operators: & | ^ ~


# A => 65 => 64 + 1 => 0100 0001
# or 0010 0000 => 32
# ---------
# a => 97 => 64 + 32 + 1 => 0110 0001
mychar = 'A'
print (mychar, ord(mychar))
mychar = chr(ord(mychar) | 32)
print (mychar, ord(mychar))

A 65
a 97

In [15]: # Bitwise operators: & | ^ ~


# a => 97 => 64 + 32 + 1 => 0110 0001
# and 1101 1111 => 255 - 32 = 223
# ---------
# A => 65 => 64 + 1 => 0100 0001
mychar = 'a'
print (mychar, ord(mychar))
mychar = chr(ord(mychar) & 223)
print (mychar, ord(mychar))

a 97
A 65

ASCII Codes
ASCII = > American Standard Code for Information Interchange (8 bits code or representation) So ASCII codes can have the value ranging from 0 to 255
(2^8 - 1) ASCII codes can be divided into two categories: 1) Normal ASCII Codes (Printable): 0 to 127 2) Extended ASCII Codes (Non-Printable): 128 to 255
(These ASCII codes can be used for control characters) a => 97, b => 98, ..., z => 122 A => 65, B => 66, ..., Z => 90 0 => 48, 1 => 49, ..., 9 => 57 Tab => 8,
Back Space => 9, Enter => 13, Esc => 27, Space Bar => 32 and so on.

In [16]: # two functions to deal with ASCII codes: chr(), ord()


print (chr(65), chr(66), chr(90), chr(97), chr(98), chr(122))
print (ord("A"), ord("B"), ord("Z"), ord("a"), ord("b"), ord("z"))

A B Z a b z
65 66 90 97 98 122

Conditional Statements
In [18]: # Problem Statement: Take three numbers from the keyboard as input and find the maximum of them and print the m
num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))
num3 = int(input("Please enter the third number: "))
if (num1 > num2):
if (num1 > num3):
print ("The first number is the maximum number...")
print ("The maximum number is", num1)
else:
print ("The third number is the maximum number...")
print ("The maximum number is", num3)
elif (num2 > num3):
print ("The second number is the maximum number...")
print ("The maximum number is", num2)
else:
print ("The third number is the maximum number...")
print ("The maximum number is", num3)
print ("End of the program...")

Please enter the first number: 10


Please enter the second number: 20
Please enter the third number: 30
The third number is the maximum number...
The maximum number is 30
End of the program...

In [19]: num1 = 100;


if (num1 % 2 == 0):
print ("This is an EVEN number...");
print ("EVEN numbers are divisible by 2...");
else:
print ("This is an ODD number...");
print ("ODD numbers are not divisible by 2...");

print()
num1 = 101
if (num1 % 2 == 0):
print ("This is an EVEN number...")
print ("EVEN numbers are divisible by 2...")
else:
print ("This is an ODD number...")
print ("ODD numbers are not divisible by 2...")

This is an EVEN number...


EVEN numbers are divisible by 2...

This is an ODD number...


ODD numbers are not divisible by 2...

Misc. Concepts
Variables initialized with any one of the values ranging from -5 to 256 (inclusive) will generate same id for same values

In [20]: num1 = 256


print (num1, type(num1), id(num1))
num2 = 256
print (num2, type(num2), id(num2))
num3 = num1
print (num3, type(num3), id(num3))

256 <class 'int'> 1804165278096


256 <class 'int'> 1804165278096
256 <class 'int'> 1804165278096

In [21]: num1 = 257


print (num1, type(num1), id(num1))
num2 = 257
print (num2, type(num2), id(num2))
num3 = num1
print (num3, type(num3), id(num3))
num4 = 257
print (num4, type(num4), id(num4))

257 <class 'int'> 1804251513808


257 <class 'int'> 1804251514160
257 <class 'int'> 1804251513808
257 <class 'int'> 1804251514320

In [22]: num1 = -5
print (num1, type(num1), id(num1))
num2 = -5
print (num2, type(num2), id(num2))
num3 = num1
print (num3, type(num3), id(num3))

-5 <class 'int'> 1804165081200


-5 <class 'int'> 1804165081200
-5 <class 'int'> 1804165081200

In [23]: num1 = -6
print (num1, type(num1), id(num1))
num2 = -6
print (num2, type(num2), id(num2))
num3 = num1
print (num3, type(num3), id(num3))
num4 = -6
print (num4, type(num4), id(num4))

-6 <class 'int'> 1804251514160


-6 <class 'int'> 1804251513872
-6 <class 'int'> 1804251514160
-6 <class 'int'> 1804251513776

In [24]: print ("Hello", "to", "all", "of", "you")


print ("Welcome")

Hello to all of you


Welcome

In [25]: help(print)

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)

Prints the values to a stream, or to [Link] by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current [Link].
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

In [26]: print ("Hello", "to", "all", "of", "you", sep = ", ")
print ("Welcome")

Hello, to, all, of, you


Welcome

In [27]: print ("Hello", "to", "all", "of", "you", sep = ", ", end = " - ")
print ("Welcome")

Hello, to, all, of, you - Welcome

In [28]: print("Gajendra "*5)


print("Anurag "*6)

Gajendra Gajendra Gajendra Gajendra Gajendra


Anurag Anurag Anurag Anurag Anurag Anurag

In [6]: # python supports variant datatype for variables, depending upon the value got assigned to the variable will de
var1 = 100
print (var1, type(var1), id(var1))
var1 = "Celebration"
print (var1, type(var1), id(var1))
var1 = 1234.56
print (var1, type(var1), id(var1))
var1 = True
print (var1, type(var1), id(var1))

100 <class 'int'> 2062221268432


Celebration <class 'str'> 2062336427568
1234.56 <class 'float'> 2062347638992
True <class 'bool'> 140721836390504

In [9]: # inbuilt collection classes and implicit objects


var1 = [1001, "Amit", "Male", "Developer", 30000.55, True]
print (var1, len(var1), type(var1), id(var1))
var1 = (1001, "Amit", "Male", "Developer", 30000.55, True)
print (var1, len(var1), type(var1), id(var1))
var1 = {"empid":1001, "empname":"Amit", "empgender":"Male", "empjob":"Developer", "empsal":30000.55, "empmarried
print (var1, len(var1), type(var1), id(var1))
var1 = {1001, "Amit", "Male", "Developer", 1001, "Amit", "Male", "Developer", 30000.55, True}
print (var1, len(var1), type(var1), id(var1))
var1 = frozenset([1001, "Amit", "Male", "Developer", 1001, "Amit", "Male", "Developer", 30000.55, True])
print (var1, len(var1), type(var1), id(var1))

[1001, 'Amit', 'Male', 'Developer', 30000.55, True] 6 <class 'list'> 2062336787456


(1001, 'Amit', 'Male', 'Developer', 30000.55, True) 6 <class 'tuple'> 2062347328768
{'empid': 1001, 'empname': 'Amit', 'empgender': 'Male', 'empjob': 'Developer', 'empsal': 30000.55, 'empmarrie
d': True} 6 <class 'dict'> 2062336488704
{30000.55, True, 'Developer', 'Amit', 1001, 'Male'} 6 <class 'set'> 2062347517056
frozenset({True, 'Amit', 1001, 'Male', 30000.55, 'Developer'}) 6 <class 'frozenset'> 2062347517280

Loop Constructs
In [27]: for i in range(10):
print (i, end = ", ")
else:
print ("\nLoop got executed successfully...")

for i in range(0, 10):


print (i, end = ", ")
else:
print ("\nLoop got executed successfully...")

for i in range(0, 10, 1):


print (i, end = ", ")
else:
print ("\nLoop got executed successfully...")

for i in range(-10, 0, 1):


print (i, end = ", ")
else:
print ("\nLoop got executed successfully...")

for i in range(1, 10, 2):


print (i, end = ", ")
else:
print ("\nLoop got executed successfully...")

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Loop got executed successfully...
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Loop got executed successfully...
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Loop got executed successfully...
-10, -9, -8, -7, -6, -5, -4, -3, -2, -1,
Loop got executed successfully...
1, 3, 5, 7, 9,
Loop got executed successfully...

In [28]: import keyword


print([Link])

['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continu
e', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'la
mbda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

In [29]: # break continue and pass statements


# using the break statement
for i in range(10):
print (i, end = ", ")
if (i == 5): break
else:
print ("\nLoop got executed successfully...")
print ("\nEnd of the program...")

0, 1, 2, 3, 4, 5,
End of the program...

In [30]: # break continue and pass statements


# using the continue statement
for i in range(10):
if (i == 5 or i == 7 or i == 8):
print ("Continuing the loop...")
continue
print ("i =", i)
else:
print ("Loop got executed successfully...")
print ("End of the program...")

i = 0
i = 1
i = 2
i = 3
i = 4
Continuing the loop...
i = 6
Continuing the loop...
Continuing the loop...
i = 9
Loop got executed successfully...
End of the program...

In [ ]: # using the break statement in while block


i = 1
while (i <= 10):
print (i, end = ", ")
if (i == 5): break
i = i + 1
else:
print ("\nLoop got executed successfully...")
print ("\nEnd of the program...")

In [31]: # using the continue statement in while block


i = 1
while (i <= 10):
if (i == 5 or i == 7 or i == 8):
print ("Continuing the loop...")
i += 1
continue
print ("i =", i)
i += 1
else:
print ("Loop got executed successfully...")
print ("End of the program...")

i = 1
i = 2
i = 3
i = 4
Continuing the loop...
i = 6
Continuing the loop...
Continuing the loop...
i = 9
i = 10
Loop got executed successfully...
End of the program...

In [32]: # example of nested loop


print ("Visit Doctor...") # 1 time
day = 1
medicount = 0
while (day <= 5):
print ("Good morning to my Family Members...") # 5 times
for medi in range(1, 4):
print (f"Day No. = {day} and Medicine No. = {medi}...") # 15 times
medicount += 1
print ("Good night to my Family Members...") # 5 times
print ("---------------------------------------------") # 5 times
day += 1
print ("Thanks to Doctor...")
print (f"Total number of medicine consumed is {medicount}...")
print ("End of the story...")

Visit Doctor...
Good morning to my Family Members...
Day No. = 1 and Medicine No. = 1...
Day No. = 1 and Medicine No. = 2...
Day No. = 1 and Medicine No. = 3...
Good night to my Family Members...
---------------------------------------------
Good morning to my Family Members...
Day No. = 2 and Medicine No. = 1...
Day No. = 2 and Medicine No. = 2...
Day No. = 2 and Medicine No. = 3...
Good night to my Family Members...
---------------------------------------------
Good morning to my Family Members...
Day No. = 3 and Medicine No. = 1...
Day No. = 3 and Medicine No. = 2...
Day No. = 3 and Medicine No. = 3...
Good night to my Family Members...
---------------------------------------------
Good morning to my Family Members...
Day No. = 4 and Medicine No. = 1...
Day No. = 4 and Medicine No. = 2...
Day No. = 4 and Medicine No. = 3...
Good night to my Family Members...
---------------------------------------------
Good morning to my Family Members...
Day No. = 5 and Medicine No. = 1...
Day No. = 5 and Medicine No. = 2...
Day No. = 5 and Medicine No. = 3...
Good night to my Family Members...
---------------------------------------------
Thanks to Doctor...
Total number of medicine consumed is 15...
End of the story...

Number Guessing Game Program In Python


In [53]: import random
Max = 20
Min = 1
guessed = [Link](Min, Max)
print(guessed)
guess = 0

while guess != guessed:


guess = int(input("Enter The New Number: "))
if guess == 0:
print("Sorry that you're giving up!")
break
elif guess > guessed:
print("Choose the Lower Value ")
elif guess < guessed:
print("Choose the Higher Value ")
else:
print("Congratulations. You made it!")

5
Enter The New Number: 1
Choose the Higher Value
Enter The New Number: 12
Choose the Lower Value
Enter The New Number: 10
Choose the Lower Value
Enter The New Number: 6
Choose the Lower Value
Enter The New Number: 4
Choose the Higher Value
Enter The New Number: 5
Congratulations. You made it!

In [57]: friends = ["Gajju", "Souvik", "Anurag","Ankan"]


for i in friends:
if i =='Anurag':
break
print(i)

Gajju
Souvik
Pattern Printing - 1 -------------------- n = 6 i . * --------------- .....* 1 5 1 (i, n) ....*** 2 4 3 . => (n - i) ...***** 3 3 5 ..******* 4 2 7 * => (2 * i - 1) .********* 5 1 9
*********** 6 0 11 --------------- Tracing Table

In [58]: n = int(input("Please enter the number of layers: "))


for i in range(1,n+1):
print ("." * (n - i) + "*" * (2 * i - 1))
print ("End of the program...")

Please enter the number of layers: 6


.....*
....***
...*****
..*******
.*********
***********
End of the program...

Python Functions
A function is a block of code that performs a specific task whenever it is called. There are two types of functions: built-in functions user-
defined functions

1. built-in functions: These functions are defined and pre-coded in python. examples: min(), max(), len(), sum(), type(), range(), dict(),
list(), tuple(), set(), print(), etc

2. user-defined functions: We can create functions to perform specific tasks as per our needs. Such functions are called user-defined
functions.

In [63]: #function takes no input arguments and returns no output arguments


def funct1():
print ("Welcome ", end = " ")
print("TIU students...")
funct1()
funct1()
funct1()
print (type(funct1), id(funct1))

Welcome TIU students...


Welcome TIU students...
Welcome TIU students...
<class 'function'> 2050537066848

In [69]: # function takes input arguments and returns no output arguments


def funct2(msg, times):
print(msg * times)

funct2("TIU is the best college \n",5)

funct2(2,5)

funct2("Anurag",5)

funct2("Good Bye !!! ", 7)

print (type(funct2), id(funct2))

TIU is the best college


TIU is the best college
TIU is the best college
TIU is the best college
TIU is the best college

10
AnuragAnuragAnuragAnuragAnurag
Good Bye !!! Good Bye !!! Good Bye !!! Good Bye !!! Good Bye !!! Good Bye !!! Good Bye !!!
<class 'function'> 2050539937856

In [74]: # function takes input arguments and also returns output arguments
def funct3(msg, times):
return (msg * times)

result = funct3("TIU is the best college \n",5)


print(result)

result = funct3(msg = "Welcome ", times = 10)


print (result)

result = funct3(times = 10,msg = "Techno ")


print (result)

print (type(funct3), id(funct3), type(result), id(result))

TIU is the best college


TIU is the best college
TIU is the best college
TIU is the best college
TIU is the best college

Welcome Welcome Welcome Welcome Welcome Welcome Welcome Welcome Welcome Welcome
Techno Techno Techno Techno Techno Techno Techno Techno Techno Techno
<class 'function'> 2050546641936 <class 'str'> 2050541132976

In [83]: # function takes input arguments and returns multiple values in collection class object as output arguments
def funct4(num1, num2):
total = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2
return total, difference, product, quotient, remainder

tt,dd,pp,qq,rr = funct4(100,40)
print (f"Total = {tt}, Difference = {dd}, Product = {pp}, Quotient = {qq}, Remainder = {rr}")
print ()

result = funct4(100, 40)


print (f"Total = {result[0]}, Difference = {result[1]}, Product = {result[2]}, Quotient = {result[3]}, Remainde

print ()
print (result, type(result), len(result), id(result))

Total = 140, Difference = 60, Product = 4000, Quotient = 2.5, Remainder = 20

Total = 140, Difference = 60, Product = 4000, Quotient = 2.5, Remainder = 20

(140, 60, 4000, 2.5, 20) <class 'tuple'> 5 2050540381744

In [88]: # function with default arguments


def funct5(par1 = 111, par2 = 222, par3 = 333): # positional parameters
print (f"par1 = {par1}, par2 = {par2} and par3 = {par3}...")

funct5(100, 200, 300) # positional arguments


funct5(100, 200)
funct5(100)
funct5()
funct5(par1 = 100, par3 = 300)
funct5(par3 = 300, par1 = 100)

par1 = 100, par2 = 200 and par3 = 300...


par1 = 100, par2 = 200 and par3 = 333...
par1 = 100, par2 = 222 and par3 = 333...
par1 = 111, par2 = 222 and par3 = 333...
par1 = 100, par2 = 222 and par3 = 300...
par1 = 100, par2 = 222 and par3 = 300...

In [92]: def funct6(par1 = 100, par2 = None):


if (par2 == None):
return par1 + par1
else:
return par1 + par2
print (funct6(100, 400))
print (funct6(100))
print (funct6(par2 = 400, par1 = 100))
print (funct6(par1 = 100))

500
200
500
200

In [28]: # function with variable number of input arguments


def funct7(*arg): # *arg defines forefully that arg is a tuple object
print (arg, len(arg), type(arg), id(arg))

funct7("Techno India", "University")


funct7("Joydeep", "Tester", "Pune", 55000, "Male", True)

('Techno India', 'University') 2 <class 'tuple'> 2350266196736


('Joydeep', 'Tester', 'Pune', 55000, 'Male', True) 6 <class 'tuple'> 2350266569632

In [31]: # function with variable number of input arguments


def funct8(**kwarg): # **kwarg defines forefully that kwarg is a dictionary object, kwarg means keyword argumen
print (kwarg, len(kwarg), type(kwarg), id(kwarg))

funct8(CollegeName="TIU",Place="Kolkata")
funct8(empname = "Joydeep", empjob = "Tester", emploc = "Pune", empsal = 55000)
funct8(empname = "Joydeep", empjob = "Tester", emploc = "Pune", empsal = 55000, empgender = "Male", empmarried =

{'CollegeName': 'TIU', 'Place': 'Kolkata'} 2 <class 'dict'> 2350268532736


{'empname': 'Joydeep', 'empjob': 'Tester', 'emploc': 'Pune', 'empsal': 55000} 4 <class 'dict'> 2350268509184
{'empname': 'Joydeep', 'empjob': 'Tester', 'emploc': 'Pune', 'empsal': 55000, 'empgender': 'Male', 'empmarrie
d': True} 6 <class 'dict'> 2350268545088

In [34]: # function with variable number of input arguments


def funct9(*arg,**kwarg):
print (arg, len(arg), type(arg), id(arg))
print (kwarg, len(kwarg), type(kwarg), id(kwarg))

funct9("Joydeep", "Tester", "Pune", empsal = 55000, empgender = "Male", empmarried = True)

print ()
funct9(empsal = 55000, empgender = "Male", empmarried = True)

print ()
funct9("Joydeep", "Tester", "Pune")

('Joydeep', 'Tester', 'Pune') 3 <class 'tuple'> 2350267568192


{'empsal': 55000, 'empgender': 'Male', 'empmarried': True} 3 <class 'dict'> 2350267770432

() 0 <class 'tuple'> 2350163443776


{'empsal': 55000, 'empgender': 'Male', 'empmarried': True} 3 <class 'dict'> 2350266081792

('Joydeep', 'Tester', 'Pune') 3 <class 'tuple'> 2350267568192


{} 0 <class 'dict'> 2350268421440

In [35]: def funct10():


i = 100
print ("Printing from within the function:", i, id(i))
i = 10
print ("Printing before calling the function:", i, id(i))
funct10()
print ("Printing after calling the function:", i, id(i))

Printing before calling the function: 10 2350163454544


Printing from within the function: 100 2350163645904
Printing after calling the function: 10 2350163454544

In [36]: i = 10
def funct10():
i = 100
print ("Printing from within the function:", i, id(i))

print ("Printing before calling the function:", i, id(i))


funct10()
print ("Printing after calling the function:", i, id(i))

Printing before calling the function: 10 2350163454544


Printing from within the function: 100 2350163645904
Printing after calling the function: 10 2350163454544

In [37]: def funct10():


global i
print ("Printing from within the function:", i, id(i))
i = 100
print ("Printing from within the function:", i, id(i))

i = 10
print ("Printing before calling the function:", i, id(i))
funct10()
print ("Printing after calling the function:", i, id(i))

Printing before calling the function: 10 2350163454544


Printing from within the function: 10 2350163454544
Printing from within the function: 100 2350163645904
Printing after calling the function: 100 2350163645904

In [39]: # non-recursive factorial function


def factorial_nr(num):
if (num == 0 or num == 1): return 1
fact = num
for i in range(2, num):
fact = fact * i
print (f"So the current value in i = {i} and fact = {fact}...")
return fact

n = 5
result = factorial_nr(n)
print (f"Non-Recursive: Factorial of {n} is {result}...")

print()
n = 7
result = factorial_nr(n)
print (f"Non-Recursive: Factorial of {n} is {result}...")

So the current value in i = 2 and fact = 10...


So the current value in i = 3 and fact = 30...
So the current value in i = 4 and fact = 120...
Non-Recursive: Factorial of 5 is 120...

So the current value in i = 2 and fact = 14...


So the current value in i = 3 and fact = 42...
So the current value in i = 4 and fact = 168...
So the current value in i = 5 and fact = 840...
So the current value in i = 6 and fact = 5040...
Non-Recursive: Factorial of 7 is 5040...
In [41]: # recursive factorial function
def factorial_r(num):
if (num == 0 or num == 1): return 1 # this is called base case where the recursion will terminate.

return num * factorial_r(num - 1) # recursive case, where the function will call itself

n = 5
result = factorial_r(n)
print (f"Recursive: Factorial of {n} is {result}...")

print()
n = 7
result = factorial_r(n)
print (f"Recursive: Factorial of {n} is {result}...")

Recursive: Factorial of 5 is 120...

Recursive: Factorial of 7 is 5040...


5! = 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (Base case) 2 6 24 120

Minor Project
In [44]: # Random Password Generator
import random
import string

def generate_password(length=12):
characters = string.ascii_letters + [Link] + [Link]
#print(characters)
password = ''.join([Link](characters) for _ in range(length))
return password

password_length = int(input("Enter the password length: "))


num_passwords = int(input("Enter the number of passwords Options you want: "))
for _ in range(num_passwords):
password = generate_password(password_length)
print(password)

Enter the password length: 10


Enter the number of passwords Options you want: 3
y>/}{'v=yO
OT='Q|V1f:
ld/Mu(&\#]

In [1]: def outer_func(x):


def inner_func(y):
return x + y
return inner_func

result = outer_func(2)(1)
print(result)

Python Lambda or Anonymous function


In [47]: mysquare = lambda num: num * num

print (type(mysquare), id(mysquare))


print (mysquare(10))
print (mysquare(9))

<class 'function'> 2557971676608


100
81

In [48]: myaddition = lambda num1, num2: num1 + num2

print (type(myaddition), id(myaddition))


print (myaddition(100, 900))
print (myaddition(400, 600))

<class 'function'> 2557971958944


1000
1000

In [50]: def funct11(num):


myprod = lambda n: n * num
return myprod
var10 = funct11(10)
var20 = funct11(20)
print (var10(3))
print (var20(4))
print (type(var10), id(var10), type(var20), id(var20))

30
80
<class 'function'> 2557971675456 <class 'function'> 2557971674592

In [52]: # lambda function with recursion


myfact = lambda num:1 if (num == 0 or num == 1) else num * myfact(num - 1)
print (myfact(5))
print (myfact(7))

120
5040

Dealing with Module: Math Module


In [53]: # importing required modules
import math

In [55]: print ([Link](0), [Link](0), [Link](0))


print ([Link](0), [Link](0), [Link](0)) # Hyperbolic cosine
print ([Link](0.5)) # Inverse Hyperbolic cosine
print ([Link](1))
print ([Link](0.5))

0.0 1.0 0.0


0.0 1.0 0.0

In [58]: # some constants in the math module


print ([Link])
print (math.e) #Euler's number 2.71...
print ([Link]) # 6.28...

3.141592653589793
2.718281828459045
6.283185307179586

In [61]: print ([Link](5), [Link](7))


print ([Link](100, 750), [Link](350, 850))
print ([Link](10, 3), 10 ** 3, 10.0 ** 3, 10 ** 3.0)

120 5040
50 50
1000.0 1000 1000.0 1000.0

In [62]: print ([Link](10.1), [Link](10.9), [Link](10.1), [Link](10.9))


11 11 10 10

In [63]: help ([Link])


Help on built-in function pow in module math:

pow(x, y, /)
Return x**y (x to the power of y).

In [64]: help (math)


Help on built-in module math:

NAME
math

DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.

FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.

The result is between 0 and pi.

acosh(x, /)
Return the inverse hyperbolic cosine of x.

asin(x, /)
Return the arc sine (measured in radians) of x.

The result is between -pi/2 and pi/2.

asinh(x, /)
Return the inverse hyperbolic sine of x.

atan(x, /)
Return the arc tangent (measured in radians) of x.

The result is between -pi/2 and pi/2.

atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.

Unlike atan(y/x), the signs of both x and y are considered.

atanh(x, /)
Return the inverse hyperbolic tangent of x.

ceil(x, /)
Return the ceiling of x as an Integral.

This is the smallest integer >= x.

comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.

Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates


to zero when k > n.

Also called the binomial coefficient because it is equivalent


to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.

Raises TypeError if either of the arguments are not integers.


Raises ValueError if either of the arguments are negative.

copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.

On platforms that support signed zeros, copysign(1.0, -0.0)


returns -1.0.

cos(x, /)
Return the cosine of x (measured in radians).

cosh(x, /)
Return the hyperbolic cosine of x.

degrees(x, /)
Convert angle x from radians to degrees.

dist(p, q, /)
Return the Euclidean distance between two points p and q.

The points should be specified as sequences (or iterables) of


coordinates. Both inputs must have the same dimension.

Roughly equivalent to:


sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

erf(x, /)
Error function at x.

erfc(x, /)
Complementary error function at x.

exp(x, /)
Return e raised to the power of x.

expm1(x, /)
Return exp(x)-1.

This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

fabs(x, /)
Return the absolute value of the float x.

factorial(x, /)
Find x!.

Raise a ValueError if x is negative or non-integral.

floor(x, /)
Return the floor of x as an Integral.

This is the largest integer <= x.

fmod(x, y, /)
Return fmod(x, y), according to platform C.

x % y may differ.

frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).

m is a float and e is an int, such that x = m * 2.**e.


If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.

fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.

Assumes IEEE-754 floating point arithmetic.

gamma(x, /)
Gamma function at x.

gcd(*integers)
Greatest Common Divisor.

hypot(...)
hypot(*coordinates) -> value

Multidimensional Euclidean distance from the origin to a point.

Roughly equivalent to:


sqrt(sum(x**2 for x in coordinates))

For a two dimensional point (x, y), gives the hypotenuse


using the Pythagorean theorem: sqrt(x*x + y*y).

For example, the hypotenuse of a 3/4/5 right triangle is:

>>> hypot(3.0, 4.0)


5.0

isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)


Determine whether two floating point numbers are close in value.

rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values

Return True if a is close in value to b, and False otherwise.

For the values to be considered close, the difference between them


must be smaller than at least one of the tolerances.

-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.

isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.

isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.

isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.

isqrt(n, /)
Return the integer part of the square root of the input.

lcm(*integers)
Least Common Multiple.

ldexp(x, i, /)
Return x * (2**i).

This is essentially the inverse of frexp().

lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.

log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.

If the base not specified, returns the natural logarithm (base e) of x.

log10(x, /)
Return the base 10 logarithm of x.

log1p(x, /)
Return the natural logarithm of 1+x (base e).

The result is computed in a way which is accurate for x near zero.

log2(x, /)
Return the base 2 logarithm of x.

modf(x, /)
Return the fractional and integer parts of x.

Both results carry the sign of x and are floats.

nextafter(x, y, /)
Return the next floating-point value after x towards y.

perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.

Evaluates to n! / (n - k)! when k <= n and evaluates


to zero when k > n.

If k is not specified or is None, then k defaults to n


and the function returns n!.

Raises TypeError if either of the arguments are not integers.


Raises ValueError if either of the arguments are negative.

pow(x, y, /)
Return x**y (x to the power of y).

prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.

The default start value for the product is 1.

When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.

radians(x, /)
Convert angle x from degrees to radians.

remainder(x, y, /)
Difference between x and the closest integer multiple of y.

Return x - n*y where n*y is the closest integer multiple of y.


In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.

sin(x, /)
Return the sine of x (measured in radians).

sinh(x, /)
Return the hyperbolic sine of x.

sqrt(x, /)
Return the square root of x.

tan(x, /)
Return the tangent of x (measured in radians).

tanh(x, /)
Return the hyperbolic tangent of x.

trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.

Uses the __trunc__ magic method.

ulp(x, /)
Return the value of the least significant bit of the float x.

DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586

FILE
(built-in)

Dealing with String Processing


String is a collection of alpha numeric and special characters. String is immutable as insert, delete and update operations can not
be carried out on a given string.

# string indexing and slicing index from left to right -> 0 1 2 3 4 5 6 7 8 9 mystr -> u n i v e r s i t y index from right to left -> -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

In [72]: mystr = "university"


print (mystr, len(mystr), type(mystr), id(mystr))
print (mystr[6], mystr[-4], mystr[8], mystr[-2], mystr[9], mystr[-1]) # indexing
print (mystr[1:6], mystr[-9:-4], mystr[1:-4], mystr[-9:6]) # slicing
print (mystr[0:6], mystr[:6], mystr[-10:-4], mystr[:-4])
print (mystr[6:], mystr[-4:])
print (mystr[3:6], mystr[-7:-4], mystr[3:-4], mystr[-7:6])
print (mystr[0::2], mystr[1::2], mystr[::-1])

university 10 <class 'str'> 2557971756912


s s t t y y
niver niver niver niver
univer univer univer univer
sity sity
ver ver ver ver
uiest nvriy ytisrevinu

You might also like