0% found this document useful (0 votes)
14 views

PYTHON M1 BIT-merged (1)

Uploaded by

akhilaswin38
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)
14 views

PYTHON M1 BIT-merged (1)

Uploaded by

akhilaswin38
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
You are on page 1/ 9

Escape Sequences : Escape sequences are the Modules refer to a file containing Python OPERATORS IN PYTHON Membership Operator

way Python expresses special characters, such statements and definitions. A file containing Arithmetic operators Operator Description Example
as the tab, the newline, and the backspace Python code, Eg. example.py, is called a module Operator Name Example In Returns True if a sequence with the
(delete key), as literals. Example↓ , and its module name would be example. We + Addition x+y specified value is present in the object
Escape Sequence use modules to break down large programs into - Subtraction x–y x in y
\’ Single quote small manageable and organized files. * Multiplication x * y Not in Returns True if a sequence with the
\\’ Double quote Furthermore, modules provide reusability of / Division x / y specified value is not present in the object
\\ Backslash code. We can define our most used functions in % Modulus x%y x not in y
\n Newline a module and import it, instead of copying their ** Exponentiation x ** y Bitwise Operator
\t Horizontal Tab definitions into different programs. // Floor division x // y Operator Name Description
\b Backspace Example : round(7.563,2) return 7.56 Assignment Operator & AND Sets each bit to 1 if both bits
Format specifiers String formatting is the abs(4-5) returns 1 Operator Example Same As are 1
process of infusing things in the string above functions belongs to __builtin__ module. = x=5 x=5 | OR Sets each bit to 1 if one of two
dynamically and presenting the string. Compiled language Interpreter language += x += 3 x=x+3 bits is 1
four different ways of string formatting:- •Compiled language •Interpreted lang. -= x -= 3 x=x–3 ^ XOR Sets each bit to 1 if only one of
•Formatting with % Operator. follows at least two follows one step to *= x *= 3 x=x*3 two bits is 1
•Formatting with format() string method. levels to get from get from source code /= x /= 3 x=x/3 ~ NOT Inverts all the bits
•Formatting with string literals, called f-strings. source code to to execution. %= x %= 3 x=x%3 << Zero fill left shift Shift left by
•Formatting with String Template Class execution. •An interpreted //= x //= 3 x = x // 3 pushing zeros in from the right and let the
TYPE CONVERSION :The input function always •A compiled lang. is language is a **= x **= 3 x = x ** 3 leftmost bits fall off
builds a string from the user’s keystrokes and converted in to language in which &= x &= 3 x=x&3 >> Signed right shift Shift right by
Returns it to the program. After inputting machine code so that the implementations |= x |= 3 x=x|3 pushing copies of the leftmost bit in from the
strings that represent numbers, programmer the processor can execute instructions ^= x ^= 3 x=x^3 left, and let the rightmost bits fall off.
must convert them from strings to appropriate execute it. directly without >>= x >>= 3 x = x >> 3 Short-Circuit Evaluation
numeric Types. In Python, there are two type •The compiled earlier compiling a <<= x <<= 3 x = x << 3 The Python virtual machine sometimes knows
conversion functions for this purpose, called programs run faster program into Comparison Operator the value of a Boolean Expression before it has
Int (for integers) and float (for floating point than interpreted machine language. Operator Name Example evaluated all of its operands. For instance, in
numbers). EXAMPLE ↓ programs. •This programs run == Equal x == y the expression A and B, if A is false, there is no
>>> first=int(input(“enter the first number: “)) •In a compiled slower than the != Not equal x != y need to Evaluate B. Likewise, in the expression
Enter the first number: 12 language, the code compiled program. > Greater than x>y A or B, if A is true, there is no need To evaluate
>>>second=int(input(“enter second number: “)) can be executed by •In this languages, < Less than x<y B. This approach, in which evaluation stops
Enter the second number: 34 the CPU. the program cannot >= Greater than or equal to x >= y ASAP, is called shortcircuit evaluation.
>>> print (“the sum is”, first+second) •This language be compiled, it is <= Less than or equal to x <= y Count = int(input(“Enter the count: “))
The sum is 46 delivers better interpreted. Logical Operator Sum = int(input(“Enter the sum: “))
INPUT FUNCTION/STATEMENT performance. •This language Operator Description Example If count > 0 and sum // count > 10:
The input() function allows a user to insert a delivers slower And Return True if both statements are true Print(“average > 10”)
value into a program. Input() returns a string . performance x < 5 and x < 10 Lazy evaluation
value. We can convert the contents of an input POSSIBLE ERRORS IN PYTHON PROGRAMMING Or Return True if one of statements is true When using any programming language, it’s
using any data type. For instance, we can •Syntax errors: Errors caused by not following x < 5 or x < 4 important to understand when Expressions are
convert the value a user inserts to a floating- the proper structure (syntax) of the language Not Reverse result, returns False if result is evaluated. Consider the simple expression:
point number. Python has an input function are called syntax or parsing errors. true not(x < 5 and x < 10) A=b=c=5 D=a+b*c
which lets you ask a user for some text input. •Runtime errors: occur during run-time. Your Identity Operator In Python,once these statements are evaluated,
We call this function to tell the program to stop code may be syntactically correct but it may Operator Description Example calculation is immediately (or strictly) carried
and wait for the user to key in the data. happen that during runtime Python encounters Is Returns True if both variables are the out, setting the value of d to 30. In another
•The form of an assignment statement with the something which it can’t handle , then it raises same object x is y programming Paradigm, such as in a pure
input function is the Following an exception. •Logical error: Occur when the Is not Returns True if both variables are not functional programming language like Haskell,
<variable identifier>=input(<a string prompt>) program runs without crashing, but produces the same object x is not y Value of d might not be evaluated until it is
• A variable identifier, or variable for short, is an incorrect result. The error is caused by a actually used elsewhere. The idea Of deferring
just a name for a value. When A variable mistake in the program’s logic . You won’t get computations in this way is commonly known
receives its value in an input statement, an error message, because no syntax or as lazy evaluation
variable then refers to This value. runtime error has occurred
The Software Development Process Composite Number To find the Sum of the digits of a number Check whether a number is Even or Odd
•The process of planning and organizing a Def isComposite(n) If (n <= 1): sum=0 n=int(input("Enter a number..")) x=int(input("Enter a number...:"))
program is called as software Development Return False If (n <= 3): Return False while n!=0: sum=sum+n%10; if x%2==0: print("number is even")
process. There are several approaches to If (n % 2 == 0 or n % 3 == 0): Return True n=n//10 print("Sum of the digits=",sum) else: print("number is odd")
software development. One version is Known I = 5 While(I * I <= n): Output: Compare two numbers
as the waterfall model. • The waterfall model If (n % I == 0 or n % (I + 2) == 0): Enter a number..123 Sum of the digits=6 x=int(input("Enter first number.."))
consists of several phases: Return True I = I + 6 Return False Find the number of digits in the factorial of a y=int(input("Enter second number.."))
1. Customer request—In this phase, the Print(“true”) if(isComposite(11)) else given nCr using a factorial function. if x>y: print("x is greater than y")
programmers receive a broad statement of a print(“false”) def fact(n): f=1 for i in range(1,n+1): elif x<y: print ("x is smaller than y")
problem .This step is also called the user Print(“true”) if(isComposite(15)) else f=f*I return f else: print ("x and y are equal")
requirements phase. print(“false”) print("Program to compute nCr...") Program to find Roots of a Quadratic Equation
2. Analysis—The programmers determine what find second largest number in a list n=int(input("Enter n..")) import math
the program will do. This is sometimes viewed list1 = [10, 20, 4, 45, 99] r=int(input("Enter r...")) print("enter a b and c the coefficients line by
as a process of clarifying the specifications for mx = max(list1[0], list1[1]) ncr=fact(n)/(fact(n-r)*fact(r)) line") a=int(input()) b=int(input())
the problem. secondmax = min(list1[0], list1[1]) print("nCr...",ncr) c=int(input()) if a==0:
3. Design—The programmers determine how n = len(list1) Output print("Not a quadratic eqtn..root is ", -c/b)
the program will do its task. for i in range(2,n): if list1[i] > mx: Program to compute nCr... else: d=b*b-4*a*c
4. Implementation—The programmers write secondmax = mx mx = list1[i] Enter n..5 Enter r...3 nCr... 10.0 if d==0: print("only one root",-b/(2*a))
program. This step is also called coding phase. elif list1[i] > secondmax and \ find the AREA of a Circle elif d>0: print("roots are real")
5. Integration—Large programs have many mx != list1[i]: secondmax = list1[i] def circlearea (radius): area=3.14*(radius**2) print("root1",-b+math.sqrt(d)/(2*a))
parts. In the integration phase, these parts are elif mx == secondmax and \ return area #function call print("root2",-b-math.sqrt(d)/(2*a))
brought together into a smoothly functioning secondmax != list1[i]: secondmax = list1[i] r=int(input("Enter radius..")) else: print("roots are imaginary")
whole, usually not an easy task. print("Second highest number is : ",\ area=circlearea(r) Input a point and find the QUADRANT
6. Maintenance—Programs usually have a long str(secondmax)) print("Area of the circle=",area) x=int(input("Enter x:")) y=int(input("enter y:"))
life; a life span of 5 to 15 years is common for Average of n numbers Output if x>0 and y >0: print("first quadrant")
software. During this time, requirements n=int(input("Enter the total number you want Enter radius..2 Area of the circle= 12.56 elif x<0 and y >0: print("second quadrant")
change, errors are detected, and minor or to enter:")) sum=0 for i in range(n): Program to check if two strings are equal elif x<0 and y <0: print("third quadrant")
major modifications are made x=int(input("Enter the number:")) sum=sum+x #first String string1 = input('Enter first string: ') elif x>0 and y <0: print("fourth quadrant")
• The figure resembles a waterfall, in which the avg=sum/n print("Average=",avg) # second string else: print("point at origin")
results of each phase flow Down to the next. Output: string2 = input('Enter second string: ') Check whether given number is PRIME or not
• However, a mistake detected in one phase Enter the total number you want to enter:4 # check strings is equal or not n=int(input("Enter a number.."))
often requires the developer to Back up and Enter the number:2 Enter the number:4 if(string1 == string2): i=2 prime=True while i<=n//2:
redo some of the work in the previous phase. Enter the number:6 Enter the number:8 print('The strings are the same.') if n%i==0: prime=False break i=i+1
Modifications Made during maintenance also Average= 5.0 else: print('The strings are not the same.') if prime==True: print('Prime number')
require backing up to earlier phases. Taken progam to reverse a number and also find the program to input a time in Seconds and Print else: print('Not a prime number')
Together, these phases are also called the sum of the digits of the number the time in HH:MM:SS format Output: Enter a number..7 Prime number
software development life cycle. rev=0 time=input("Enter time in seconds") Enter a number..4 Not a Prime number
• Modern software development is usually print("Enter a number") time=int(time) timeinmin=time//60 program to find the sum of even numbers
incremental and iterative. This Means that num=int(input()) timeinsec=time%60 timeinhr=timeinmin//60 from N given numbers
analysis and design may produce a rough draft, while num!=0: timeinmin=timeinmin%60 sum=0
skeletal version, Or prototype of a system for d=num%10 print("HH:MM::SS---- N=int(input("enter the number of numbers
coding, and then back up to earlier phases to fill rev=rev*10+d {}:{}:{}".format(timeinhr,timeinmin,timeinsec)) (N)..")) print("Enter Numbers")
In more details after some testing. num=num//10 find AREA and CIRCUMFERENCE of a CIRCLE for i in range(N): num=int(input())
• Keep in mind that mistakes found early are print("Reverse of the number=",rev) #Standard formula to calculate the Area of a if num%2==0: sum=sum+num
much less expensive to correct Than those output circle is: a=π r². #Circumference c=2 π r. print("Sum of even numbers..",sum)
found late. These are not just financial costs but Enter a number import math r=input("Enter radius :") Output:
also costs in time And effort. 123 r=int(r) Enter the number of numbers (N)..5
a=math.pi * r * r Enter 5 Numbers
c=2* math.pi * r 4 2 6 8 1
print("Area of the circle",a) Sum of even numbers.. 20
print ("Circumference of the circle",c)
program which takes a positive integer n as Check Armstrong number of n digits Variable Scopes and Life time LAMBDA Functions A lambda is an anonymous
input and finds the sum of cubes of all positive Eg:1634= 1**4+6**4+3**4+4**4=1634 •Scope of a variable is the portion of a program function. • It has no name of its own, but
even numbers less than or equal to number. Ans: where the variable is recognized. Parameters contains the names of its arguments as well as
sum=0 num =int(input("Enter a number...")) and variables defined inside a function are not a single expression.• When lambda is applied to
N=int(input("enter the number")) # Changed num variable to string, and visible from outside the function. Hence, they its arguments, its expression is evaluated, and
for num in range(1,N+1): if num%2==0: calculated the length (number of have a local scope.• The lifetime of a variable is its value is returned. • syntax of a lambda is
sum=sum+num**3 digits) the period throughout which the variable exits lambda <argname-1,… ,argname-n >:
print("Sum of cubes of even numbers..",sum) order = len(str(num)) in the memory. The lifetime of variables inside <expression>
output # initialize sum a function is as long as the function executes. • All of the code must appear on one line and a
enter the number 5 sum = 0 • They are destroyed once we return from the lambda cannot include a selection statement,
Sum of cubes of even numbers.. 72 # find the sum of the cube of each digit function. Hence, a function does not remember Bcoz, selection statements aren’t expressions.
Generate first 10 Fibonacci numbers temp = num the value of a variable from its previous calls. Eg: x=lambda x,y:x+y
a=0 b=1 for i in range(10): while temp > 0: •Here is an example to illustrate the scope of a print(x(2,3)) output will be 5
c=a+b a=b b=c print(c) digit = temp % 10 variable inside a function. RECURSIVE FUNCTION Recursion is the process
ouput 1 2 3 5 8 13 21 34 55 89 sum += digit ** order def my_func(): of defining something in terms of itself.
Print Prime numbers less than 1000 temp //= 10 x = 10 print("Value inside function:",x) Recursive function is a function that calls itself.
print("Prime numbers less than 1000") # display the result x = 20 my_func() print("Value outside To prevent a function from repeating itself
for n in range(2,1000): if num == sum: function:",x) indefinitely, it must contain at least one
i=2 while i<=n/2: if n%i==0: print(num,"is an Armstrong number") Output selection statement. This statement examines a
break i=i+1 else: print (n,end=' ') else: Value inside function: 10 condition called a base case to determine
Write a Nested loop to print the following print(num,"is not an Armstrong number") Value outside function: 20 whether to stop or to continue with another
pattern output FUNCTIONS :A function is a block of code recursive step. Example ↓
54321 Enter a number...1634 which only runs when it is called. You can pass Program to print factorial of a number
4321 1634 is an Armstrong number data, known as parameters, into a function. A # recursively.
321 program that display decimal equivalent of a function can return data as a result. def recursive_factorial(n):
21 string of bits. •In Python, a function is a group of related if n == 1: return n else:
1 USE float() TO CONVERT STRING TO DECIMAL statements that performs a specific task. return n * recursive_factorial(n-1)
Ans: Call float(x) to convert a string x to a decimal. • Function help break our program into smaller # user input num = 6
n=int(input("Enter a number::")) pi = "3.14159" & modular chunks. As our program grows larger # check if the input is valid or not
for i in range(n,0,-1): decimal = float(pi) and larger, functions make it more organized if num < 0:
for j in range(i,0,-1): print(decimal) and manageable. •Furthermore, it avoids print("Invalid input ! Enter a positive number.")
print (j,end=' ') print() OUTPUT repetition and makes the code reusable. elif num == 0:
Print Multiplication table of 1-n numbers 3.14159 Syntax of Function print("Factorial of number 0 is 1")
n=int(input("Enter n::")) program that display decimal number to a def function_name(parameters): else:
for k in range(1,n+1): string of bits statement(s) print("Factorial of number", num, "=",
for i in range(1,11): from decimal import Decimal Creating a Function In Python a function is recursive_factorial(num))
print(k ,"X",i,"=",k*i) dec = Decimal(10) defined using def keyword: Advantages of using Recursion
print() print(dec, type(dec)) Eg: def my_function(): •A complicated function can be split down into
# Converting to string print("Hello from a function") smaller sub-problems utilizing recursion.
dec = str(dec) Calling a Function To call a function, use the •Sequence creation is simpler through
print(dec, type(dec)) function name followed by parenthesis: recursion than utilizing any nested iteration.
Eg: def my_function(): •Recursive functions render the code look
print("Hello from a function") simple and effective.
my_function() # calling a function Disadvantages of using Recursion
Advantages of Functions •A lot of memory and time is taken through
•Reducing duplication of code recursive calls which makes it expensive for
•Decomposing complex problems into simpler use. •Recursive functions are challenging to
pieces debug. •The reasoning behind recursion can
•Improving clarity of the code sometimes be tough to think through.
•Reuse of code
•Information hiding
LIST : •list is a sequence of data values called DICTIONARY Methods STRING Methods/FUNCTIONS File Access Modes Access modes govern the
items or elements in item can be of any type. •Get() Method return the value for the given •find() Searches the string for a specified value type of operations possible in the opened file. It
•List is a non-homogeneous data structure that key if present in the dictionary. If not, then it and returns the position of where it was found refers to how file will be used once its opened.
stores elements in single row and multiple rows will return None Eg: txt = "Hello, welcome to my world." 1. Read Only (‘r’) : Open text file for reading.
& columns • List can be represented by [ ]. Eg: d = {‘coding’: ‘good’, ‘thinking’: ‘better’} x = txt.find("welcome") The handle is positioned at beginning of file. If
• List allows duplicate elements. • List can use Print(d.get(‘coding’)) print(x) the file does not exists, raises the I/O error. This
nested among all • List can be created using •pop() method removes and returns the •count() method returns the number of times is also default mode in which a file is opened.
list() function • List is mutable i.e we can make specified element from the dictionary. a specified value appears in the string. 2. Read and Write (‘r+’): Open the file for
any changes in list.•Each of the items in a List is Eg: # create a dictionary Eg: txt = "I love apples, apple are my favorite reading and writing. The handle is positioned at
ordered by position. Marks={ ‘Physics’: 67, ‘Chemistry’: 72, ‘Math’: fruit" x = txt.count("apple", 10, 24) print(x) the beginning of the file. Raises I/O error if the
Eg: Creating an empty list l=[] 89} Element = marks.pop(‘Chemistry’) •center() method will center align the string, file does not exist.
•List of strings [‘apples’,’oranges’] Print(‘Popped Marks:’, element) using a specified character (space is default) as 3. Write Only (‘w’) : Open the file for writing.
•List of integers [1343, 3242, 2443] # Output: Popped Marks: 72 the fill character. For the existing files, the data is truncated and
TUPLE: is a non-homogeneous data structure •Keys() method in Python Dictionary, returns a Eg: txt = "banana" over-written. The handle is positioned at the
that stores single row and multiple rows and view object that displays a list of all the keys in x = txt.center(20, "O") print(x) beginning of the file. Creates the file if the file
columns •Tuple can be represented by ( ) the dictionary in order of insertion using Python •isalpha() method returns True if all the does not exist.
•Tuple allows duplicate elements •Tuple can Eg: numbers = {1: 'one', 2: 'two', 3: 'three'} characters are alphabet letters (a-z). 4. Write and Read (‘w+’) : Open the file for
use nested among all •Tuple can be created # extracts the keys of the dictionary Example of characters that are not alphabet reading and writing. For an existing file, data is
using tuple() function. •Tuple is immutable i.e dictionaryKeys = numbers.keys() letters: (space)!#%&? etc. truncated and over-written. The handle is
we can not make any changes in tuple. print(dictionaryKeys) Eg: txt = "CompanyX" positioned at the beginning of the file.
•Each of items in a Tuple is ordered by position. # Output: dict_keys([1, 2, 3]) x = txt.isalpha() print(x) 5. Append Only (‘a’): Open the file for writing.
• Creating an empty Tuple t=() •update() method updates the dictionary with •isdigit() method returns True if all characters The file is created if it does not exist. The
Eg: >>> fruits ("apple", "banana") the elements from another dictionary object or are digits, otherwise False. Exponents, like ², handle is positioned at the end of the file. The
>>> fruits from an iterable of key/value pairs. are also considered to be a digit. data being written will be inserted at the end,
('apple', 'banana') Eg: marks = {'Physics':67, 'Maths':87} Eg: txt = "50800" after the existing data.
>>> meats ("fish", "poultry") internal_marks = {'Practical':48} x = txt.isdigit() print(x) 6. Append and Read (‘a+’) : Open the file for
>>> meats marks.update(internal_marks) SETS METHODS/ OPERATIONS reading and writing. The file is created if it does
('fish', 'poultry') print(marks) MethodDescription not exist. The handle is positioned at the end of
DICTIONARY is a non-homogeneous data # Output: {'Physics': 67, 'Maths': 87, 'Practical': •Add() Adds an element to the set the file. The data being written will be inserted
structure which stores key value pairs 48} •Clear() Removes all the elements from set at the end, after the existing data.
•Dictionary can be represented by { } •values() is an inbuilt method in Python •Copy() Returns a copy of the set Python code to create a function called
•Set will not allow duplicate elements and programming language that returns a view •Difference() Returns a set containing the list_of_frequency that takes a string and prints
dictionary doesn’t allow duplicate keys. object. The view object contains the values of difference between two or more sets letters in non-increasing order of frequency of
•Dictionary can use nested among all the dictionary, as a list. If you use the type() •Difference_update() Removes items in this their occurrences. Use dictionaries.
•Dictionary can be created using dict() function. method on the return value, you get set that also included in another, specified set
•Dictionary is mutable. But Keys are not “dict_values object”. It must be cast to obtain •Discard() Remove the specified item
duplicated. •Dictionary is ordered (Python 3.7 the actual list. •Intersection() Returns a set, that is the
and above)• Creating an empty dictionary d={} Eg: marks = {'Physics':67, 'Maths':87} intersection of two or more sets
example dictionaries: print(marks.values()) •Intersection_update() Removes items in this
A phone book: {'Savannah':'476-3321', # Output: dict_values([67, 87]) set that not present in other, specified set(s)
'Nathaniel':"'351-7743'} •items() method is used to return the list with •union() Return a set containing union of sets
Personal information: ('Name':'Molly', 'Age':18} all dictionary keys with values. •issubset() Returns whether another set
SET : data structure is non-homogeneous Eg: marks = {'Physics':67, 'Maths':87} contains this set or not
data structure but stores in single row •Set can print(marks.items())
be represented by { } •Set will not allow # Output: dict_items([('Physics', 67), ('Maths', Difference b/w TEXT FILE & BINARY FILE
duplicate elements •Set can use nested among 87)]) A text file consists of human readable
all •Set can be created using set() function characters, which can be opened by any text
•Set is mutable i.e we can make any changes in editor. while, binary files consist of non-human
set. But elements are not duplicated. •Set is readable characters and symbols, which require
unordered •Creating a set a=set() b=set(a) specific programs to access its contents.
check whether a given year is a leap year/not program for Palindrome checking without PROGRAM TO DRAW HEXAGON USING Blurring an Image
3.Input 4 integers(+ve and –ve).Write a Python reversing the string TURTLE # import the turtle modules ➔This algorithm resets each pixel’s color to the
code to find the sum of negative s=input("Enter the string...") import turtle average of the colors of the four pixels that
numbers, positive numbers and print them. if s==s[::-1]: print("palindrome..") # Start a work Screen surround it.➔The function blur expects an
Also find the averages of these two else: print("not palindrome...") ws = turtle.Screen() image as an argument and returnsa copy of that
groups of numbers and print Palindrome checking using loop # Define a Turtle Instance image with blurring.➔The function blur begins
psum=0 nsum=0 pc=0 nc=0 s=input("Enter the string..") Turtle = turtle.Turtle() its traversal of grid with position (1, 1) and ends
print("Enter the 4 Numbers +ve and -ve") beg=0 end=len(s)-1 while beg<end: # executing loop 6 times for 6 sides with position (width, height).
➔means that the algorithm does not transform
for i in range(4): if s[beg]!=s[end]: print("Not palindrome") for i in range(6):
num=int(input()) if num>0: Break beg+=1 end-=1 # Move forward by 90 units
the pixels on the image’s outer edges.
psum=psum+num pc=pc+1 else: Print("Palindrome") Turtle.forward(90)
EVENT DRIVEN PROGRAMMING the flow of a
else: nsum=nsum+num nc=nc+1 program to read an integer number . Print the # Turn left the turtle by 300 degrees
program depends upon the events, and
print("Sum of +ve numbers..",psum) reverse of this number using recursion. Turtle.left(300)
programming which focuses on events is called
if pc!=0:print("Avg of +ve numbers..",psum/pc) # Reverse a number using recursion image processing function in Python
Event-Driven programming. We were only
print("Sum of -ve numbers..",nsum) def reverse(n, r): if n==0: return r >Converting an Image to Black and White
dealing with either parallel or sequential
if nc!=0:print("Avg of -ve numbers..",nsum/nc) else: return reverse(n//10, r*10 + n%10)
models, but now we will discuss the
output # Read number
asynchronous model. The programming model
Enter the 4 Numbers +ve and -ve number = int(input("Enter number: "))
following the concept of Event-Driven
2 3 -4 -1 # Function call
programming is called t Asynchronous model.
Sum of +ve numbers.. 5 reversed_number = reverse(number,0)
Working of Event-Driven programming depends
Avg of +ve numbers.. 2.5 # Display output upon events happening in a program. Other
Sum of -ve numbers.. -5 print("Reverse of %d is %d" %(number, than this, it depends upon the program’s event
Avg of -ve numbers.. -2.5 reversed_number))
loops that always listen to a new incoming
Write a Python program to find the value for find maximum of two numbersusing lampda
event in the program. Once an event loop starts
sin(x) up to n terms using the series a=2;b=4 in program, then only events will decide what
sin(x)-(x/1!)-(x^3/3!)+(x^5/5!)-(x^7/7!)+… maximum = lambda a,b:a if a > b else b
>Converting an Image to Grayscale will execute and in which order.
where x is in degrees print(f'{maximum(a,b)} is a maximum number')
Black-and-white photographs are not really A Loop Pattern for Traversing a Grid:/
import math def sinseries(x,n): python code to find maximum of two numbers Row-major traversal in a two-dimensional grid.
just black and white; they also contain various
sine = 0 for i in range(n): using list comprehension
shades of gray known as grayscale uses a nested loop structure to traverse a two-
sign = (-1)**I x=x*(math.pi/180) a=2;b=4
. dimensional grid of pixels. Each data value in
sine = sine + x=[a if a>b else b]
grid is accessed with a pair of coordinates using
((x**(2.0*i+1))/math.factorial(2*i+1))*sign print("maximum number is:",x)
the form (<column>, <row>)
return sine maximum of two numbers using function
x=int(input("Enter the value of x in degrees:")) def maximum(a, b):
n=int(input("Enter the number of terms:")) if a >= b: return a else:
print(round(sinseries(x,n),2)) return b # Driver code
output: a=2 b=4
Enter the value of x in degrees:30 print(maximum(a, b))
Enter the number of terms:10 to read first 10 characters from a file named
0.5 Note: you can replace factorial() function “data.txt” create a text file data.txt with Copying an Image The Image class includes a
in math module with your own function some characters the write python file clone method, Method clone builds and
print even length words in string ,keep the two files in the same folder returns a new image with same attributes as
#input string open(“data.txt”,”r”) original one, but with an empty string as
n="This is a python language" data = f.read(10) filename.
#splitting the words in a given string print(data)
s=n.split(" ") for i in s:
#checking the length of words
if len(i)%2==0:
print(i)
Qn. Write a GUI-based program that allows self._CelsValue = Entry(self, font = font, fg =
TERMINAL BASED PROGRAMS : The terminal- The Structure of Any GUI Program the user to convert temperature values "red", justify = "center", width = 13,
based program prompts the user for user from breezypythongui import EasyFrame between degrees Fahrenheit and degrees textvariable = self._celsVar)
inputs and other program dependant values. class <class name>(EasyFrame) : Celsius. The interface should have labeled self._CelsValue.grid(row = 1, column = 1)
•After the user enters his inputs, the program def __init__(self): entry fields for these two values. These # The command buttons
responds by computing and displaying the EasyFrame._init_(self <optional args>) components should be arranged in a grid self._button = Button(self, font = font,
results. Program then terminates execution. <code to set up widgets> where the labels occupy the first row and the text = " >>>> ", command =
Terminal-based user interface : has several <code to define event-handling methods> corresponding fields occupy the second row. self._FahrValueN)
obvious effects on its users:•The user is # Instantiates and pops up the window. At start-up, the Fahrenheit field should font = tkinter.font.Font(family = "Arial", size =
constrained to reply to a definite sequence of If __ name__==”__ main": contain 32.0, and the Celsius field should 15)
prompts for inputs.•Once an input is entered, <class name>().mainloop() contain 0.0. The third row in window contains self._button.grid(row = 2, column = 0,
there is no way to back up and change it. two command buttons, labeled >>>> and columnspan = 1)
•To obtain results for a different set of input <<<<. When the user presses the first button, self._button = Button(self, font = font,
data, the user must run the program again and the program should use the data in the text = " <<<< ", command = self._CelsValue)
all of the inputs must be re-entered. Fahrenheit field to compute Celsius value, font = tkinter.font.Font(family = "Arial", size =
These problems for users can be solved by which should be o/p to Celsius field. Second 15)
converting the interface to a GUI. button should perform inverse function. self._button.grid(row = 2, column = 1,
The GUI-Based PROGRAM from tkinter import * columnspan = 1)
→ The GUI-based version of the program import tkinter.messagebox #### From here down is not to be indented
displays a window that contains various class _TemperatureConversion(Frame): #### Just indented to keep it in the window
components, also called widgets (eg: Button, Turtle Operations def __init__(self): def _fahrenheitToCelsius(FahrValue):
Textbox..) →A GUI program is event driven, #Sets up the window and widget Fahr = FahrValue
that it is inactive until the user clicks a button Frame.__init__(self) Cels = ((Fahr - 32) * 5) / 9 print(Cels)
or selects a menu option.→ A title bar at the self.master.title("Temperature Conversion") def _celsiusToFahrenheit(CelsValue):
top of the window. •This bar contains the title self.master.rowconfigure(0, weight = 5) Cels = CelsValue Fahr = ((Cels * 9) / 5) +
of the program, “Tax Calculator.” • Three self.master.columnconfigure(0, weight = 5) 32
colored disks. Each disk is a command self.master.geometry("300x300") print(Fahr)
button.•The user can use the mouse to click self.master.resizable(0,0) def main():
the left disk to quit the program • the middle self.grid(rowspan = 1, columnspan = 1) _TemperatureConversion().mainloop()
disk to minimize the window, or the right disk # Calculates the Fahrenheit to Celsius FahrValue = float(input("Enter a Fahrenheit
to zoom the window.• The user can also move conversion value to convert: "))
the window around the screen by holding left turtle attributes font = tkinter.font.Font(family = "Arial FConvert = fahrenheitToCelsius(FahrValue)
mouse button on title bar and dragging mouse. Black", size = 15) CelsValue = float(input("Enter a Celsius value
Accessor Method: This method is used to self._fahrLabel = Label(self, font = font, text to convert: "))
access the state of the object i.e, the data = " Fahrenheit ") CConvert = celsiusToFahrenheit(CelsValue)
hidden in the object can be accessed from this self._fahrLabel.grid(row = 0, column = 0)
method. However, this method cannot change self._fahrVar = DoubleVar() Object Instantiation and the turtle Module
the state of the object, it can only access the font = tkinter.font.Font(family="Arial", size=13) ➔ Before use a Turtle object, must create them.
data hidden. We can name these methods with self._FahrValue = Entry(self, font = font, fg = ➔ That is create an instance of the object’s
the word get. "blue", justify = "center", width = 13, class.
Mutator Method: This method is used to textvariable = self._fahrVar, text = "32.0",) ➔ The process of creating an object is called
➔ instantiation .
mutate/modify the state of an object i.e, it Drawing Two-Dimensional Shapes self._FahrValue.grid(row = 1, column = 0)
alters the hidden value of the data variable. It # Calculates the Celsius to Fahrenheit
from turtle import Turtle
can set the value of a variable instantly to a conversion
t = Turtle()
➔ A window is created with the turtle’s icon is
new value. This method is also called as update font = tkinter.font.Font(family = "Arial
method. Moreover, we can name these Black", size = 15)
located at the home
methods with the word se self._celsLabel = Label(self, font = font, text =
position (0, 0) in the center of the window,
" Celsius ")
facing east and ready to
self._celsLabel.grid(row = 0, column = 1)
draw.
➔ The user can resize the window in the usual
self._celsVar = DoubleVar()
font= tkinter.font.Font(family = "Arial",size=13)
manner.
Write a Python program to find the quadrant Qn. A bouncy program is defined as follows – CLASS INSTATIATION IN PYTHON : Write Python program to create a class called
of a point, say (x,y). The program computes and displays total Instantiating a class is creating a copy of class as Complex and implement__add__( ) method
# for initialization of coordinates distance traveled by a ball, given 3 inputs—the which inherits all class variables and methods. to add two complex numbers. Display the
X, y = map(int, list(input(“Insert the value for initial height from which it is dropped, its Instantiating a class in Python is simple. To result by overloading the + Operator.
variable X and Y : “).split(“ “))) bounciness index, and number of bounces. instantiate a class, we simply call the class as if class Complex ():
# find true condition of first quadrant Given the inputs write a GUI-based program to it were a function, passing the arguments that def initComplex(self):
If x > 0 and y > 0: compute total distance traveled. the __init__ method defines. The return value self.realPart = int(input("Enter the Real Part: "))
Print(“point (“, x, “,”, y, “) lies in the First from tkinter import * will be the newly created object. self.imgPart = int(input("Enter the
quadrant”) master = Tk() Example: Imaginary Part: "))
# find second quadrant master.title("Bouncy") Class Foo(): def display(self):
Elif x < 0 and y > 0: def BouncyCalc(): Def __init__(self,x,y): print(self.realPart,"+",self.imgPart,"i", sep="")
Print(“point (“, x, “,”, y, “) lies in the Second z = float(b_index.get()) ** Print x+y def sum(self, c1, c2):
quadrant”) (float(num_bounce.get()) + 1) F = Foo(3,4) self.realPart = c1.realPart + c2.realPart
# To find third quadrant return float(height_e.get()) * (1 + (2 * (z / Output : 7 self.imgPart = c1.imgPart + c2.imgPart
Elif x < 0 and y < 0: (float(b_index.get()) - 1)))) Qn. Write a Python program to express the c1 = Complex()
Print(“point (“, x, “,”, y, “) lies in the Third Label(master, text="Initial Height").grid(row=0) instances as return values to define a class c2 = Complex()
quadrant”) Label(master, text = "Bounciness RECTANGLE with parameters height, width, c3 = Complex()
# To find Fourth quadrant Index").grid(row = 1) corner_x, and corner_y and member functions print("Enter first complex number")
Elif x > 0 and y < 0: Label(master, text = "Number of to find center,area, &perimeter of an instance. c1.initComplex()
Print(“point (“, x, “,”, y, “) lies in the Fourth Bounces").grid(row = 2) class Rectangle(): print("First Complex Number: ", end="")
quadrant”) height_e = Entry(master) def __init__(self, l, w): c1.display()
# To find does not lie on origin b_index = Entry(master) self.length = l print("Enter second complex number")
Elif x == 0 and y == 0: num_bounce = Entry(master) self.width = w c2.initComplex()
Print(“point (“, x, “,”, y, “) lies at the origin”) height_e.insert(10,"0.0") def rectangle_area(self): print("Second Complex Number: ", end="")
# On x-axis b_index.insert(10,"0.0") return self.length*self.width c2.display()
Elif y == 0 and x != 0: num_bounce.insert(10, "0") newRectangle = Rectangle(12, 10) print("Sum of two complex numbers is ",
Print(“point (“, x, “,”, y, “) on x-axis”) height_e.grid(row = 0, column = 1) print(newRectangle.rectangle_area()) end="")
# On y-axis b_index.grid(row = 1, column = 1) Write a Python class named Circle constructed c3.sum(c1,c2)
Elif x == 0 and y != 0: num_bounce.grid(row = 2, column = 1) by a radius and two methods which will c3.display()
Print(“point (“, x, “,”, y, “) on at y-axis”) calc_button = Button(master, text = "Calculate", compute area and perimeter of a given circle Polymorphism in Python
command = BouncyCalc()) class Circle(): The word polymorphism means having many
calc_button.grid(row = 3, column = 1) def __init__(self, r): forms. In programming, polymorphism means
mainloop() self.radius = r same function name (but different signatures)
def area(self): being uses for different types. • It is a very
return self.radius**2*3.14 important concept in programming. It refers to
def perimeter(self): the use of a single type entity (method,
return 2*self.radius*3.14 operator or object) to represent different types
NewCircle = Circle(8) in different scenarios.
print(NewCircle.area()) Eg: Polymorphism in addition operator
print(NewCircle.perimeter()) num1=1
Output: 200.96 num2=2
50.24 print(num1+num2) o/p:3
• ZeroDivisionError: This exception is raised comp1 = Complex(2, 3)
when you provide the second argument for a comp2 = Complex(5, -2)
division or modulo operation as zero. solve(comp1, comp2)

Handling an Exception Write a Python program to implement the Inheritance in Python Def father(self):
Eg: a=True addition, subtraction, and multiplication Inheritance is an important aspect of the Print(self.fathername)
while a: ofcomplex numbers using classes. Use object-oriented paradigm. Inheritance provides # Derived class
x=int(input("Enter a number: ")) constructors to create objects. Theinput to the code reusability to the program because we can Class Son(Mother, Father):
print("Dividing 50 by", x, "will give you:", 50/x) program consist of real and imaginary parts of use an existing class to create a new class Def parents(self):
You will get Value Error on entering decimal the complex numbers instead of creating it from scratch. Print(“Father :”, self.fathername)
number or string as input. • In inheritance, the child class acquires the Print(“Mother :”, self.mothername)
from math import sqrt
To handle the exception, properties and can access all the data members # Driver’s code
class Complex:
The first step of the process is to include the and functions defined in the parent class. A S1 = Son()
code that you think might raise an exception def __init__(self, real, imag): child class can also provide its specific S1.fathername = “ABC”
inside the try clause. The next step is to use the self.re = real implementation to functions of parent class. S1.mothername = “DEF”
except keyword to handle the exception that self.im = image Syntax: S1.parents()
occurred in the above code def __add__(self, o): class derived class name (base class): Output:
a = True return Complex(self.re+o.re, self.im+o.im) <class-suite> Father : ABC
while a: def __sub__(self, o): Single Inheritance :Single inheritance enables a Mother : DEF
try: return Complex(self.re-o.re, self.im-o.im) derived class to inherit properties from a single Multilevel Inheritance :
x=int(input("Please enter a number: ")) def __mul__(self, o): parent class, thus enabling code reusability and In multilevel inheritance, features of the base
print("Dividing 50 by", x, "will give you: ", 50/x) return Complex(self.re*o.re-self.im*o.im, the addition of new features to existing code. class and the derived class are further inherited
except ValueError: self.re * o.im + self.im * o.re) Eg: # Python program to demonstrate into the new derived class. This is similar to a
print("The input was not an integer. Please try # single inheritance relationship representing a child and a
again...") def __truediv__(self, o): # Base class grandfather.
Output: m = o.re * o.re + o.im * o.im class Parent: Eg: # Python program to demonstrate
Please enter a number: a def func1(self): # multilevel inheritance
Input was not an integer. Please try again... return Complex((self.re * o.re + self.im * print("This function is in parent class.") # Base class class Grandfather:
Please enter a number: 2 o.im)/m, (self.im * o.re - self.re * o.im)/m) # Derived class def __init__(self, grandfathername):
Dividing 50 by 2 will give you: 25.0 class Child(Parent): self.grandfathername = grandfathername
def __str__(self):
def func2(self): #Intermediate class class Father(Grandfather):
Some Common Built-in Exceptions if self.im == 0: print("This function is in child class." def __init__(self, fathername,
• NameError: This exception is raised when the return '%.2f' % self.re # Driver's code grandfathername):
program cannot find a local or global name. The if self.re == 0: object = Child() self.fathername = fathername
name that could not be found is included in the object.func1() # invoking constructor of Grandfather class
error message. return '%.2fi' % self.im object.func2() Grandfather.__init__(self, grandfathername)
•TypeError: This exception is raised when a Output: # Derived class class Son(Father):
function is passed an object of the if self.im < 0: This function is in parent class. def __init__(self, sonname, fathername,
inappropriate type as its argument. More return '%.2f - %.2fi' % (self.re, -self.im) This function is in child class. grandfathername):
details about the wrong type are provided in Multiple Inheritance: self.sonname = sonname
else:
the error message. When a class can be derived from more than # invoking constructor of Father class
return '%.2f + %.2fi' % (self.re, self.im)
•ValueError: This exception occurs when a one base class this type of inheritance is called Father.__init__(self, fathername,
function argument has the right type but an def mod(self): return multiple inheritances. In multiple inheritances, grandfathername def print_name(self):
inappropriate value. sqrt(self.re*self.re+self.im*self.im) all the features of the base classes are inherited print('Grandfather name :',
•NotImplementedError: This exception is def solve(comp1, comp2): into the derived class. self.grandfathername)
raised when an object is supposed to support print(comp1 + comp2) Eg: # Python program to demonstrate print("Father name :", self.fathername)
an operation but it has not been implemented print(comp1 - comp2) # multiple inheritance print("Son name :", self.sonname) #Driver code
yet. You should not use this error when the print(comp1 * comp # Base class1 s1 = Son('Prince', 'Rampal', 'Lal mani')
given function is not meant to support the type print(comp1 / comp2) Class Mother: print(s1.grandfathername)
of input argument. In those situations, raising a print('%.2f' % comp1.mod()) Mothername = “” s1.print_name()
TypeError exception is more appropriate. print('%.2f' % comp2.mod()) Def mother(self): Output:
Print(self.mothername) Lal mani
# Base class2 Grandfather name : Lal mani
Class Father: Father name : Rampal
Fathername = “” Son name : Prince
Hierarchical Inheritance: Hybrid Inheritance:
When more than one derived class are created Inheritance consisting of multiple types of
from a single base this type of inheritance is inheritance is called hybrid inheritance.
called hierarchical inheritance. In this program, Eg: # Python program to demonstrate
we have a parent (base) class and two child # hybrid inheritance
(derived) classes. class School:
Eg # Python program to demonstrate def func1(self):
# Hierarchical inheritance print("This function is in school.")
# Base class class Student1(School):
class Parent: def func2(self):
def func1(self): print("This function is in student 1. ")
print("This function is in parent class.") class Student2(School):
# Derived class1 def func3(self):
class Child1(Parent): print("This function is in student 2.")
def func2(self): class Student3(Student1, School):
print("This function is in child 1.") def func4(self):
# Derivied class2 print("This function is in student 3.")
class Child2(Parent): # Driver's code
def func3(self): object = Student3()
print("This function is in child 2.") object.func1()
# Driver's code object.func2()
object1 = Child1() Output:
object2 = Child2() This function is in school.
object1.func1() This function is in student 1.
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

You might also like