Printing Techniques and Python Basics
Printing Techniques and Python Basics
Heading-1
Heading-2
Heading-3
Heading-4
Heading-5
Heading-6
Heading-1
Heading-2
Heading-3
Heading-4
Heading-5
Heading-6
In [3]: '''
This is a multi line comment
'''
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...")
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
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 [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)
EVEN Number
ODD Number
100
110
100
1000
1000000
A 65
a 97
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.
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...")
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...")
Misc. Concepts
Variables initialized with any one of the values ranging from -5 to 256 (inclusive) will generate same id for same values
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))
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))
In [25]: help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)
In [26]: print ("Hello", "to", "all", "of", "you", sep = ", ")
print ("Welcome")
In [27]: print ("Hello", "to", "all", "of", "you", sep = ", ", end = " - ")
print ("Welcome")
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))
Loop Constructs
In [27]: for i in range(10):
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...
['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']
0, 1, 2, 3, 4, 5,
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...
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...
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...
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!
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
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.
funct2(2,5)
funct2("Anurag",5)
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)
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 ()
print ()
print (result, type(result), len(result), id(result))
500
200
500
200
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 =
print ()
funct9(empsal = 55000, empgender = "Male", empmarried = True)
print ()
funct9("Joydeep", "Tester", "Pune")
In [36]: i = 10
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))
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}...")
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}...")
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
result = outer_func(2)(1)
print(result)
30
80
<class 'function'> 2557971675456 <class 'function'> 2557971674592
120
5040
3.141592653589793
2.718281828459045
6.283185307179586
120 5040
50 50
1000.0 1000 1000.0 1000.0
pow(x, y, /)
Return x**y (x to the power of y).
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.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
ceil(x, /)
Return the ceiling of x as an Integral.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
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.
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!.
floor(x, /)
Return the floor of x as an Integral.
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).
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> 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
-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).
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.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
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.
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.
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.
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.
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)
# 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