Data Visualization Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Data Visualization Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Data Visualization Class 12 Notes

What is Data Visualization

The process of displaying data in the form of graphs or charts is known as data visualisation. It makes it incredibly simple to understand big and complex volumes of data. It makes decision-making very efficient and makes it simple for decision-makers to spot emerging trends and patterns. We can utilise a variety of Python data visualisation libraries, like Matplotlib, Seaborn, Plotly, etc.

Using Pylot of Matplotlib Library

The Python low-level package Matplotlib is used for data visualisation. It is simple to use and replicates the graphs and visualisation found in MATLAB. This library is composed of numerous plots, including line charts, bar charts, histograms, etc.

An interface similar to MATLAB is offered by the Matplotlib package Pyplot. Because it supports Python and is free and open-source, Matplotlib is intended to be just as functional as MATLAB. Each Pyplot function modifies a figure in some way, such as by creating a figure, a plotting region within the figure, some lines within the plot area, labelling the plot, etc.

Data Visualization Class 12 Notes

Installing and Importing matplotlib

Your machines already have the matplotlib library loaded if you installed Python using Anaconda. By launching Anaconda Navigator, you may verify it for yourself. Click Environments in the Navigator box, then scroll down then you can find list of installed software on your machine.

Data Visualization Class 12 Notes

Using NumPy Array

NumPy (‘Numerical Python’ or ‘Numeric Python’, pronounced as Num Pie) is an open source module of Python that offers functions and routines for fast mathmaatical computation on arrays and matrices. In order to use NumPy, you must import in your module by using a statemnt like –

import numpy as np

Code
import numpy as np
list = [1, 2, 3, 4]
a1 = np.array(list)
print(a1)

Data Visualization Class 12 Notes

Ways to create NumPy arrarys

a) Creating a One-dimensional Array
To create a One dimensional Array the arange function is frequently used to quickly build an arrary. The arange method generates an array with values from 0 to 9 when given a value of 10.

Example
import Numpy as np
array = np.arange(20)
array

Output
array([0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19])

Data Visualization Class 12 Notes

b) Creating a Two-dimensional Array
Let’s discuss how to make a two-dimensional array. The output of the arange function, when used alone, is a one-dimensional array. Combine its output with the reshape function to convert it to a two-dimensional array.

Example
array = np.arange(20).reshape(4,5)
array

Output
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])

Data Visualization Class 12 Notes

Creating Charts with Matplotlib Library’s Pyplot interface

You know that graphs and charts play a big and an important role in data visualization and decision making. Every chart type has a different utility and serves a different purpose.
a) Line Chart – A line chart or line graph is a type of chart which displays information as a series of data points called ‘Markers’ connected by straight line segments. The PyPlot interface offers plot() function for creating line graph.

Example
import matplotlib.pyplot as plt
x = [5, 10, 20, 30]
y = [10, 15, 25, 35]
plt.plot(x, y)
plt.title(“Line Chart”)
plt.ylabel(‘Y-Axis’)
plt.xlabel(‘X-Axis’)
plt.show()

b) Bar Chart – A bar Graph or a Bar Chart is a graphical display of data using bars of different heights. A bar chart can be drawn vertically or horizontally using rectangles or bars of different heights/ widths PyPlot offer bar() function to create a bar chart.

Example
import matplotlib.pyplot as plt
x = [5, 10, 20, 30]
y = [10, 15, 25, 35]
plt.plot(x, y)
plt.title(“Line Chart”)
plt.ylabel(‘Y-Axis’)
plt.xlabel(‘X-Axis’)
plt.show()

Data Visualization Class 12 Notes

c) The Pie Chart – Recall that a pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. Typically, a Pie Chart is used to show parts to the whole, and often a % share. The PyPlot interface offers pie() function for creating a pie chart.

Example
import matplotlib.pyplot as plt
x = [5, 10, 20, 30]
y = [10, 15, 25, 35]
plt.plot(x, y)
plt.title(“Line Chart”)
plt.ylabel(‘Y-Axis’)
plt.xlabel(‘X-Axis’)
plt.show()

Idea of Efficiency in Python Class 12

idea of efficiency in python class 12

Teachers and Examiners (CBSESkillEduction) collaborated to create the Idea of Efficiency in Python Class 12. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Idea of Efficiency in Python Class 12

Idea of Algorithmic Efficiency

A sufficiently accurate method or process that can be programmed into a computer and is used to carry out a given task is known as an algorithm. Numerous internal and external elements affect an algorithm’s performance, or should we say quality.

Internal Factors
a) Time required to run
b) Space required to run

External Factors
a) Size of the input to the algorithm
b) Speed of the computer on which it is run
c) Quality of the compiler

Idea of Efficiency in Python Class 12

What is computational complexity

When analysing algorithms, computational complexity is a important factor. The words “compulation” and “complexity” are combined to form the term “compulation complxity.” The computation includes the issues that need to be resolved and the algorithms used to do so. In order to understand how much resource is required or adequate for this algorithm to operate effectively, complexity theory is used.

The resource generally include
a) The time to run the algorithm
b) The space needed to run the algorithm

Estimating Complexity of Algorithms
Algorithmic complexity considers how quickly or slowly a specific algorithm operates. The mathematical function T(n) – time versus the input size n is how we define complexity. Without relying on implementation specifics, we wish to specify how long an algorithm takes.

Big-O Natation

Big O Notation is a technique for expressing how time-consuming an algorithm is. As the input increases, it calculates how long it will take to perform an algorithm. In other words, it determines an algorithm’s worst-case time complexity. The maximum runtime of an algorithm is expressed using the Big O Notation in data structures.

Idea of Efficiency in Python Class 12

Dominant Term

The growth rate is shown using the Big-O notation. By going inside the algorithm, one can find the category of mathematical formulas that most accurately captures the behaviour of an algorithm. The term that grows the quickest is the dominating term.

Common Growth Rates

Some growth rates of algorithms are as shown in following table –
a) O(1) – Constant
b) O(log N) – Log
c) O(N) – Linear
d) O(N log N) – n Log n
e) O(N2) – Quadratic
f) O(N3) – Cubic
g) O(2N) – Exponential

Idea of Efficiency in Python Class 12

Guidelines for Computing Complexity

The five guidelines for finding out the time complexity of a piece of code are –
a) Loops – The running time of a loop is , at most, equal to the running time of the stateemnts inside the loop multiplied by the number of iteration.

b) Nested Loops – To compute complexity of nested loops, analyze inside out. For nested loops, total running time is the product of the sizes of the loops.

c) Consecutive Statement – To compute the complexity of consecutive statement, simply add the time complexities of each statement.

d) If-then-else Statements – To compute time complexity of it-then-else statement, we consider worst-case running time, Which means, we consider the time taken by the test, plus taken by either the then part or the else part.

e) Logarithmic Complexity – The logarithmic complexity means that an algorithms performance time has logarithmic factor e.g. an algorithm is O(log N) if it takes a constant time to cut the problem size by a fraction.

Idea of Efficiency in Python Class 12

Best, Average and Worst case complexity

1) Best case – quickest turnaround time with optimal inputs. For instance, data that has already been sorted would be the best case scenario for a sorting algorithm.
2) Worst case – is the slowest completion speed, with pessimistic inputs.
3) Average case – mean equals average scenario.

Recursion in Python Class 12

Recursion in Python Class 12

Teachers and Examiners (CBSESkillEduction) collaborated to create the Recursion in Python Class 12. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Recursion in Python Class 12

Recursion in Python

Python allows for the recursion of functions, which allows a defined function to call itself. A popular idea in mathematics and computer programming is recursion.

There are two types of Recursion in Python. Function calls itself directly form within its body is an example of direct recursion. However, if a function calls another function which calls its caller function from within its body is known as indirect recursion.

Example
Direct recursion
def a() :
a()

Indirect recursion
def a() :
b()

Recursion in Python Class 12

The Two Laws of Recursion

  1. Must have a base case – At least one basic requirement or condition must be met before the function can stop calling itself.
  2. Must move toward the base case – The recursive calls should progress so that each time they get closer to the initial requirements.

Advantages of using Recursion

1. Recursion can be used to break a complex function into smaller problems.
2. Recursion is more efficient at creating sequences than any nested iteration.
3. Recursive functions make the code appear straightforward and efficient.

Disadvantages of using Recursion

1. Recursive consume a lot of memory and time.
2. Debugging recursive functions can be difficult.

Recursion in Python Class 12

How recursion works in python

The function is called repeatedly through recursion from within the function. The repeated calls to the function are carried out by the recursive condition up until the base case is satisfied.

Factorial of a Number Using Recursion

def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)
f=factorial(5)
print (“factorial of 5 is “,f)

Output
factorial of 5 is 120

Fibonacci numbers Using Recursion

def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input(“enter a number”))
if n <= 0:
print(“Enter a positive Number”)
else:
print(“Fibonacci sequence:”)
for i in range(n):
print(fibonacci(i))

Output
enter a number10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Recursion in Python Class 12

Binary Search Using Recursion

def b_Search (arr, first, last, x):
if last >= first:
mid =int( first + (last – first)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return b_Search(arr, first, mid-1, x)
else:
return b_Search(arr, mid+1, last, x)
else:
return -1
arr = [ 1,3,5,6,7,8,10,13,14 ]
x = 10
result = b_Search(arr, 0, len(arr)-1, x)
if result != -1:
print (“Position of the Element is %d” % result)
else:
print (“Element not found”)

Output
Element is present at index 6
> 10

File Handling in Python Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the File Handling in Python Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

File Handling in Python Class 12 Notes

File Handling in Python

File handling is the process of saving data in a Python programme in the form of outputs or inputs, The python file can be store in the form of binary file or a text file. There are six different types of modes are available in Python programming language.

1. r – read an existing file by opening it.
2. w – initiate a write operation by opening an existing file. If the file already has some data in it, it will be overwritten; if it doesn’t exist, it will be created.
3. a – Open a current file to do an add operation. Existing data won’t be replaced by it.
4. r+ – Read and write data to and from the file. It will replace any prior data in the file.
5. w+ – To write and read data, use w+. It will replace current data.
6. a+ – Read and add data to and from the file. Existing data won’t be replaced by it.

File Handling in Python Class 12 Notes

In Python, File Handling consists of following three steps

  • Open the file
  • Read and Write operation
  • Close the file

Opening and Closing file in Python

The file must first be opened before any reading, writing, or editing operations may be carried out. It must first be opened in order to create any new files. The file needs to be closed after we are finished using it. If we forgot to close the File, Python automatically closes files when a programme finishes or a file object is no longer referenced in a programme.

Example
open()
close()

File Handling in Python Class 12 Notes

Create a file using write() mode in Python

The write() mode is used to creating or manipulating file in Python.

Example
# Create a file in python
file = open(‘example.txt’,’w’)
file.write(“I am Python learner”)
file.write(“Welcome to my School”)
file.close()

Read a file using read() mode in Python

You can read the data from binary or text file in Python using read() mode.

Example
file = open(‘example.txt’, ‘r’)
print (file.read())

Write a file using append() mode in Python

You can add multiple line of data in the file using append() mode in Python.

Example
file = open(‘example.txt’, ‘a’)
file.write(“The text will added in exicesiting file”)
file.close()

File Handling in Python Class 12 Notes

Write a file using with() function mode in Python

You can also write the file using the with() mode in Python.

Example
with open(“example.txt”, “w”) as f:
f.write(“Welcome to my School”)

Split lines in a file using split() mode in Python

You can also split lines using file handling in Python.

Example
with open(“example.text”, “r”) as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

File Handling in Python Class 12 Notes

Flush() function in File

When you write onto a file using any of the write functions, Python holds everthing to write in the file in buffer and pushes it onto actual file on storage device a leter time. If however, you want ot foce Python to write the contents of buffer onto storage, you can use flush() function. Python automatically flushes the files when closing them.

Example
f = open(‘example.text’, ‘w+’)
f.write(‘Welcome to my School’)
f.flush()

File Handling in Python Class 12 Notes

Difference between Text file and Binary file

Text File – A text file is one whose contents may be examined using a text editor. Simply put, a text file is a collection of ASCII or Unicode characters. Text files include things like Python programmes and content created in text editors.

Binary File – A binary file is one whose content is stored in the form of binary, which consists of a series of bytes, each of which is eight bits long. Word documents, MP3 files, picture files, and .exe files are a few example of binary files.

Using Python Libraries Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Using Python Libraries Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Using Python Libraries Class 12 Notes

Python Library

Python library is a collection of codes or modules of codes that may be used by a programme to do particular activities. We use libraries to avoid having to rewrite code that is already present in our programme.

Python standard library

  • Pandas
  • Numpy
  • SciPy
  • Scrapy
  • Matplotlib
  • TensorFlow

Example
# Importing math library
import math

num = 32
print(math.sqrt(num))

Using Python Libraries Class 12 Notes

Python Modules

A file containing definitions and statements in Python is known as a module. Functions, classes, and variables can all be defined using modules. Runnable code might also be a part of a module. The code is simpler to comprehend and utilise when similar code is gathered into a module. It also organises the code logically.

Example
# Creating simple code of Module in python
def addition(a, b):
return (a+b)

def subtraction(a, b):
return (a-b)

Importing Module in Python

Example
import calc

print(calc.add(22, 2))

Advantage of module

  • It reduces the complexity of the program
  • You can create well defined program in python
  • You can use same program many times

Using Python Libraries Class 12 Notes

Importing Modules

A programme can import modules using the import statement in Python. There are two ways to use the import statement.

  • Use the import <module> command is used to import a full module.
  • The from “module” import “object” command can be used to import specific objects from a module.
Importing Entire Module in Python

The appropriate module name must be used along with the import keyword. The import statement causes the interpreter to add the module to the current programme when it encounters one. By adding the dot (.) operator to the module name, you can call the functions contained within a module.

Example
import math
n = 25
print(math.sqrt(n))

Importing Selected Objects in Python

You can also import single or multiple objects in python using the following syntax –

from <module name> import <object name1>, <object name2>, <object name3>

Using Python Libraries Class 12 Notes

Mathematical and String Function

1. oct(<integer>) – Returns octal string for given number.

Example
x = oct(32)
print(x)

Output
0o40

2. hex(<integer>) – Returns hex string for given number.

Example
x = hex(32)
print(x)

Output
0x20

3. int(<number) – Truncates the fractional part of given number and returns only the integer or whole part.

Example
x = int(32.6)
print(x)

Output
32

4. round(<number>, [<ndigits>]) – Returns number rounded to ndigits after the decimal points. If ndigits is not given, it returns nearest integer to its input.

Example
x = round(7.3554, 2)
print(x)

Output
7.36

5. <Str>.join(<String iterable>) – Joins a string or character after each memeber of the string iterator.

Example
myTuple = (“Amit”, “Rakesh”, “Rajesh”)
x = “#”.join(myTuple)
print(x)

Output
Amit#Rakesh#Rajesh

6. <Str>.split(<string / char>) – Splits a string based on given string or character and returns a list containing split strings are members.

Example
str = “welcome to my School”
x = str.split()
print(x)

Output
[‘welcome’, ‘to’, ‘my’, ‘School’]

Using Python Libraries Class 12 Notes

7. <Str>.replace(<word to be replaced>, <replace word>) – Replaces a word or part of the string with another in the given string <str>.

Example
str = “welcome to my School”
x = str.replace(“School”, “Home”)
print(x)

Output
welcome to my Home

8. random() – It returns a random floating point number N in the range [0.0, 1.0]

Example
import random
myList = [1, 2, 3, 4, 5]
print(random.choice(myList))

9. randint(a,b) – It returns a random integer N in the range (a,b).

Example
import random
print(random.randint(3, 9))

Disclaimer – 100% of the information are taken from the Computer Science textbook written by Sumita Arora, and our team has tried to collect all the correct Notes from the textbook. If you found any suggestion or any error please contact us anuraganand2017@gmail.com.

Working with Functions in Python Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Working with Functions in Python Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Working with Functions in Python Class 12 Notes

Define functions in Python

A function is a block of code that only executes when called. You can supply parameters—data—to a function. As a result, a function may return data. You can define function using def keyword.

Syntax for defining function –

def <function name> (<parameters>) :
<statement 1>
<statement 2>
.
.
.

Flow of execution in a function call

The flow of execution refers to the order in which statements are executed during a program run. The program’s opening statement is where execution always starts. The statements are carried out one at a time, in ascending order. Although the order in which a programme runs is unaffected by function declarations, keep in mind that statements inside a function are not performed until the function is called.
Example –
Defining function
def sum(x, y) :

Calling function
sum(a,b)

Where a, b are the values being passed to the function sum().

Passing parameters in function

Information that is supplied into a function is referred to as a parameter or argument. The terms parameter and argument can both be used to refer to the same thing. The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like.

Python supports three types of formal arguments/parameters
1. Positional arguments – Arguments that must be presented in the right order are known as positional arguments. When calling a function, the first positional argument must always be listed first and the second will be in second.

2. Default arguments – If no argument value is given during the function call, default values will be passed in the function.

3. Keyword arguments – When values are supplied into a function, they are known as keyword arguments . The assignment operator, =, and a parameter come before a keyword argument.

Using multiple argument types together

Python allows you to combine multiple argument types in a function call. Consider the following function call statement that is using both positional arguments and keyword arguments.

interest(5000, time = 5)

Rules for combining all three types of arguments

  • An argument list must first contain positional arguments followed by any keyword argument.
  • Keyword arguments should be taken from the required arguments preferably.
  • You cannot specify a value for an argument more than once.

Returning values from functions

Functions in Python may or may not return a value. You already known about it. There can be broadly two types of functions in python.
a. Function returning some value (non-void functions)
b. Function not returning any value (void functions)

Composition

A concept that represents a relationship is composition. Composition in general refers to using an expression as part of a larger expression; or a statement as a part of larger statement. In functions context, we can understand composition as follows –

Example

An arithmetic expression
greater((4+5), (3+4))
A logical expression
test(a or b)
A function call (function composition)
int(str(52))
int(float(“52.5”)*2)
int(str(52) + str(10))

Scope of Variable

The rules that determine which areas of the programme a specific piece of code or data item would be known as and be accessible within are known as a language’s scope rules.

There are two types of scopes in Python.

  1. Global Scope
  2. Local Scope

Global Scope – A name defined in a program’s top-level (_main) segment is said to have a global scope and be usable throughout the entire programme and all blocks contained therein.

Local Scope – Local scope describes a name that is declared in the body of a function. It can only be utilized in this function and the other blocks that are placed beneath it. The formal arguments’ names also have a local scope.

Mutable/Immutable Properties of Passed Data Objects

Type of Function

There are two types of function in python.

  1. User – Define Function
  2. Built – in – Function

The Python language includes built-in functions such as dir, len, and abs. The def keyword is used to create functions that are user specified.

Working with Functions in Python Class 12 Notes

User – Define Function

User-defined functions are the fundamental building block of any programme and are essential for modularity and code reuse because they allow programmers to write their own function with function name that the computer can use.

Creating User Defined Function

A function definition begins with def (short for define). The syntax for creating a user defined function is as follows –

Syntax – 

def function_name(parameter1, parameter2, …) :
statement_1
statement_2
statement_3
….

  • The items enclosed in “[ ]” are called parameters and they are optional. Hence, a function may or may not have parameters. Also, a function may or may not return a value.
  • Function header always ends with a colon (:).
  • Function name should be unique. Rules for naming identifiers also applies for function naming.
  • The statements outside the function indentation are not considered as part of the function.

Q. Write a user defined function to add 2 numbers and display their sum.

#Program
#Function to add two numbers
def addnum():
fnum = int(input(“Enter first number: “))
snum = int(input(“Enter second number: “))
sum = fnum + snum
print(“The sum of “,fnum,”and “,snum,”is “,sum)
#function call
addnum()

Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11

Working with Functions in Python Class 12 Notes

Arguments and Parameters

User-defined function could potentially take values when it is called. A value received in the matching parameter specified in the function header and sent to the function as an argument is known as an argument.

Q. Write a program using a user defined function that displays sum of first n natural numbers, where n is passed as an argument.

#Program
#Program to find the sum of first n natural numbers
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum + i
print(“The sum of first”,n,”natural numbers is: “,sum)
num = int(input(“Enter the value for n: “))
sumSquares(num) #function call

Q. Write a program using a user defined function myMean() to calculate the mean of floating values stored in a list.

#Program 7-6
#Function to calculate mean
def myMean(myList):
total = 0
count = 0
for i in myList:
total = total + i
count = count + 1
mean = total/count
print(“The calculated mean is:”,mean)
myList = [1.3,2.4,3.5,6.9]
myMean(myList)

Output:
The calculated mean is: 3.5250000000000004

Q. Write a program using a user defined function calcFact() to calculate and display the factorial of a number num passed as an argument.

#Program 7-7
#Function to calculate factorial
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print(“Factorial of”,num,”is”,fact)
num = int(input(“Enter the number: “))
calcFact(num)

Output:
Enter the number: 5
Factorial of 5 is 120

String as Parameters

Some programmes may require the user to supply string values as an argument.

Working with Functions in Python Class 12 Notes

Q. Write a program using a user defined function that accepts the first name and lastname as arguments, concatenate them to get full name and displays the output as:

#Program
#Function to display full name
def fullname(first,last):
fullname = first + ” ” + last
print(“Hello”,fullname)
first = input(“Enter first name: “)
last = input(“Enter last name: “)
fullname(first,last)

Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan

Working with Functions in Python Class 12 Notes

Default Parameter

The argument can be given a default value in Python. When a function call doesn’t have its appropriate argument, a default value is chosen in advance and given to the parameter.

Q. Write a program that accepts numerator and denominator of a fractional number and calls a user defined function mixedFraction() when the fraction formed is not a proper fraction. The default value of denominator is 1. The function displays a mixed fraction only if the fraction formed by the parameters does not evaluate to a whole number.

#Program
#Function to display mixed fraction for an improper fraction
def mixedFraction(num,deno = 1):
     remainder = num % deno
     if remainder!= 0:
         quotient = int(num/deno)
         print(“The mixed fraction=”, quotient,”(“,remainder, “/”,deno,”)”)
     else:
         print(“The given fraction evaluates to a whole number”)
num = int(input(“Enter the numerator: “))
deno = int(input(“Enter the denominator: “))
print(“You entered:”,num,”/”,deno)
if num > deno:
     mixedFraction(num,deno)
else:
     print(“It is a proper fraction”)

Output:
Enter the numerator: 17
Enter the denominator: 2
You entered: 17 / 2
The mixed fraction = 8 ( 1 / 2 )

Working with Functions in Python Class 12 Notes

Functions Returning Value

The function’s values are returned using the return statement. A function that has finished its duty will return a value to the script or function that called it.

The return statement does the following –

  • returns the control to the calling function.
  • return value(s) or None.

Q. Write a program using user defined function calcPow() that accepts base and exponent as arguments and returns the value Baseexponent where Base and exponent are integers.

#Program
#Function to calculate and display base raised to the power exponent
def calcpow(number,power):
result = 1
for i in range(1,power+1):
result = result * number
return result
base = int(input(“Enter the value for the Base: “))
expo = int(input(“Enter the value for the Exponent: “))
answer = calcpow(base,expo)
print(base,”raised to the power”,expo,”is”,answer)

Output:
Enter the value for the Base: 5
Enter the value for the Exponent: 4
5 raised to the power 4 is 625

Flow of Execution

The first statement in a programme is where the Python interpreter begins to carry out the instructions. As they read from top to bottom, the statements are carried out one at a time.
The statements contained in a function definition are not executed by the interpreter until the function is called.

Scope of a Variable

An internal function variable can’t be accessed from the outside. There is a well defined accessibility for each variable. The scope of a variable is the area of the programme that the variable is accessible from. A variable may fall under either of the two scopes listed below:
A variable with a global scope is referred to as a global variable, whereas one with a local scope is referred to as a local variable.

Global Variable – A variable that is defined in Python outside of any function or block is referred to as a global variable. It is accessible from any functions defined afterward.

Local Variable – A local variable is one that is declared inside any function or block. Only the function or block where it is defined can access it.

Working with Functions in Python Class 12 Notes

Built-in functions

The pre-made Python functions that are widely used in programmes are known as built-in functions. Let’s examine the subsequent Python programme –

#Program to calculate square of a number
a = int(input(“Enter a number: “)
b = a * a
print(” The square of “,a ,”is”, b)

In the programme mentioned above, the built-in functions input(), int(), and print() are used. The Python interpreter already defines the set of instructions that must be followed in order to use these built-in functions.

built in functions

Commonly used built-in functions

Function
Syntax
ArgumentsReturnsExample
Output
abs(x)x may be an integer or floating point numberAbsolute value of xabs(4)
4
abs(-5.7)
5.7
divmod(x,y)x and y are integersA tuple: (quotient, remainder)divmod(7,2)
(3, 1)
divmod(7.5,2)
(3.0, 1.5)
divmod(-7,2)
(-4, 1)
max(sequence)
or
max(x,y,z,…)
x,y,z,.. may be integer or floating point numberLargest number in the sequence/ largest of two or more argumentsmax([1,2,3,4])
4
max(“Sincerity”)
‘y’ #Based on ASCII value
max(23,4,56)
56
min(sequence)
or
min(x,y,z,…)
x, y, z,.. may be integer or floating point numberSmallest number in the sequence/ smallest of two or more argumentsmin([1,2,3,4])
1
min(“Sincerity”)
‘S’
Uppercase letters have
lower ASCII values than
lowercase letters.
min(23,4,56)
4
pow(x,y[,z])x, y, z may be integer or floating point numberxy (x raised to the power y)
if z is provided, then: (xy ) % z
pow(5,2)
25.0
pow(5.3,2.2)
39.2
pow(5,2,4)
1
sum(x[,num])x is a numeric
sequence and num
is an optional
argument
Sum of all the
elements in the
sequence from left to
right.
if given parameter,
num is added to the
sum
sum([2,4,7,3])
16
sum([2,4,7,3],3)
19
sum((52,8,4,2))
66
len(x)x can be a sequence
or a dictionary
Count of elements
in x
len(“Patience”)
8
len([12,34,98])
3
len((9,45))
2 >>>len({1:”Anuj”,2:”Razia”,
3:”Gurpreet”,4:”Sandra”})
4

Working with Functions in Python Class 12 Notes

Module

The Python standard library includes a number of modules. A module is a collection of functions, whereas a function is a collection of instructions. suppose we have created some functions in a program and we want to
reuse them in another program. In that case, we can save those functions under a module and reuse them. A module is created as a python (.py) file containing a collection of function definitions.

To use a module, we need to import the module. Once we import a module, we can directly use all the functions
of that module. The syntax of import statement is as follows:

import modulename1 [,modulename2, …]

Built-in Modules

Let’s examine a few widely used modules and the functions that are contained in such modules:

Module name : math
Function
Syntax
ArgumentsReturnsExample
Output
math.ceil(x)x may be an integer or floating point numberceiling value of xmath.ceil(-9.7)
-9
math.ceil (9.7)
10
math.ceil(9)
9
math.floor(x)x may be an integer or floating point numberfloor value of xmath.floor(-4.5)
-5
math.floor(4.5)
4
math.floor(4)
4
math.fabs(x)x may be an integer or floating point numberabsolute value of xmath.fabs(6.7)
6.7
math.fabs(-6.7)
6.7
math.fabs(-4)
4.0
math.factorial(x)x is a positive integerfactorial of xmath.factorial(5)
120
math.fmod(x,y)x and y may be an
integer or floating point
number
x % y with sign of xmath.fmod(4,4.9)
4.0
math.fmod(4.9,4.9)
0.0
math.fmod(-4.9,2.5)
-2.4
math.fmod(4.9,-4.9)
0.0
math.gcd(x,y)x, y are positive integersgcd (greatest common divisor) of x and ymath.gcd(10,2)
2
math.pow(x,y)x, y may be an integer or
floating point number
xy (x raised to the power y)math.pow(3,2)
9.0
math.pow(4,2.5)
32.0
math.pow(6.5,2)
42.25
math.pow(5.5,3.2)
233.97
math.sqrt(x)x may be a positive
integer or floating point
number
square root of xmath.sqrt(144)
12.0
math.sqrt(.64)
0.8
math.sin(x)x may be an integer or
floating point number in
radians
sine of x in radiansmath.sin(0)
0
math.sin(6)
-0.279

Working with Functions in Python Class 12 Notes

Module name : random
Function
Syntax
ArgumentReturnExample
Output
random.random()No argument (void)Random Real Number (float) in the range 0.0 to 1.0random.random()
0.65333522
random.randint(x,y)x, y are integers such that x <= yRandom integer between x and yrandom.randint(3,7)
4
random.randint(-3,5)
1
random.randint(-5,-3)
-5.0
random.randrange(y)y is a positive integer signifying the stop valueRandom integer between 0 and yrandom.randrange(5)
4
random.randrange(x,y)x and y are positive integers signifying the start and stop valueRandom integer between x and yrandom.randrange(2,7)
2

Working with Functions in Python Class 12 Notes

Module name : statistics
Function SyntaxArgumentReturnExample
Output
statistics.mean(x)x is a numeric sequencearithmetic meanstatistics.mean([11,24,32,45,51])
32.6
statistics.median(x)x is a numeric sequencemedian (middle value) of xstatistics.median([11,24,32,45,51])
32
statistics.mode(x)x is a sequencemode (the most repeated value)statistics.mode([11,24,11,45,11])
11
statistics.mode((“red”,”blue”,”red”))
‘red’

Python Revision Tour 1 Class 12 MCQ

Teachers and Examiners (CBSESkillEduction) collaborated to create the Python Revision Tour 1 Class 12 MCQ. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Python Revision Tour 1 Class 12 MCQ

1. An ordered set of instructions to be executed by a computer to carry out a specific task is called a ___________.
a. Program 
b. Instruction
c. Code
d. None of the above

Show Answer ⟶
a. Program

2. Computers understand the language of 0s and 1s which is called __________.
a. Machine language
b. Low level language
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

3. A program written in a high-level language is called _________.
a. Language
b. Source code 
c. Machine code
d. None of the above

Show Answer ⟶
b. Source code

4. An interpreter read the program statements _________.
a. All the source at a time
b. One by one 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. One by one

5. Python is a __________.
a. Low level language
b. High level language 
c. Machine level language
d. All of the above

Show Answer ⟶
b. High level language

6. Python is __________.
a. Open source language
b. Free language
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

7. Python support __________.
a. Compiler
b. Interpreter 
c. Assembler
d. None of the above

Show Answer ⟶
b. Interpreter

8. Python programs are ___________.
a. Easy to understand
b. Clearly defined syntax
c. Relatively simple structure
d. All of the above 

Show Answer ⟶
d. All of the above

9. Python is _________.
a. Case – sensitive 
b. Non case – sensitive
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Case – sensitive

10. Python is platform independent, meaning ___________.
a. It can run various operating systems
b. It can run various hardware platforms
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

11. Python uses indentation for __________.
a. Blocks
b. Nested Blocks
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

12. To write and run (execute) a Python program, we need to have a ___________.
a. Python interpreter installed on the computer
b. We can use any online python interpreter
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

13. The interpreter is also called python _______.
a. Shell 
b. Cell
c. Program
d. None of the above

Show Answer ⟶
a. Shell

14. To execute the python program we have to use __________.
a. Interactive mode
b. Script mode
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

15. __________ allows execution of individual statements instantaneously.
a. Interactive mode 
b. Script mode
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Interactive mode

16. _________allows us to write more than one instruction in a file called Python source code.
a. Interactive mode
b. Script mode 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Script mode

17. To work in the interactive mode, we can simply type a Python statement on the ________ prompt directly.
a. >>> 
b. >>
c. >
d. None of the above

Show Answer ⟶
a. >>>

18. In the script mode, we can write a Python program in a ________, save it and then use the interpreter to execute it.
a. Prompt
b. File 
c. Folder
d. All of the above

Show Answer ⟶
b. File

19. By default the python extension is __________.
a. .py 
b. .ppy
c. .pp
d. .pyy

Show Answer ⟶
a. .py

20. __________ are reserved words in python.
a. Keyword 
b. Interpreter
c. Program
d. None of the above

Show Answer ⟶
a. Keyword

21. The rules for naming an identifier in Python are ________.
a. Name should begin with an uppercase, lowercase or underscore
b. It can be of any length
c. It should not be a keyword
d. All of the above 

Show Answer ⟶
d. All of the above

22. To define variables in python _______ special symbols is not allowed.
a. @
b. # and !
c. $ and %
d. All of the above 

Show Answer ⟶
d. All of the above

23. A variable in a program is uniquely identified by a name __________.
a. Identifier 
b. Keyword
c. Code
d. None of the above

Show Answer ⟶
a. Identifier

24. Variable in python refers to an ________.
a. Keyword
b. Object 
c. Alphabets
d. None of the above

Show Answer ⟶
b. Object

25. The variable message holds string type value and so its content is assigned within _________.
a. Double quotes “”
b. Single quotes ”
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

26. _________ must always be assigned values before they are used in expressions.
a. Keyword
b. Variable 
c. Code
d. None of the above

Show Answer ⟶
b. Variable

27. ___________ are used to add a remark or a note in the source code.
a. Keyword
b. Source
c. Comment 
d. None of the above

Show Answer ⟶
c. Comment

28. __________ are not executed by a python interpreter.
a. Keyword
b. Source
c. Comment 
d. None of the above

Show Answer ⟶
c. Comment

29. In python comments start from _______.
a. # 
b. @
c. %
d. $

Show Answer ⟶
a. #

30. Python treats every value or data item whether numeric, string, or other type (discussed in the next section) as an _________.
a. Object 
b. Variable
c. Keyword
d. None of the above

Show Answer ⟶
a. Object

31. _________ identifies the type of data values a variable can hold and the operations that can be performed on that data.
a. Data type 
b. Data base
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Data type

32. Number data type classified into ________.
a. int
b. float
c. complex
d. All of the above 

Show Answer ⟶
d. All of the above

33. ________ data type is a subtype of integer
a. Boolean 
b. string
c. list
d. None of the above

Show Answer ⟶
a. Boolean

34. A Python sequence is an ordered collection of items.
a. Number
b. Sequence 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Sequence

35. Sequence data type is classified into _________.
a. Strings
b. Lists
c. Tuples
d. All of the above 

Show Answer ⟶
d. All of the above

36. __________ is a group of characters in python.
a. Number
b. String 
c. Boolean
d. All of the above

Show Answer ⟶
b. String

37. In the string data type you can store __________.
a. Alphabets
b. Digits
c. Special character including space
d. All of the above 

Show Answer ⟶
d. All of the above

38. _________ is a sequence of items separated by commas and the items are enclosed in square brackets [ ].
a. List 
b. Tuple
c. String
d. None of the above

Show Answer ⟶
a. List

39. __________ is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
a. List
b. Tuple 
c. String
d. None of the above

Show Answer ⟶
b. Tuple

40. _________ is an unordered collection of items separated by commas and the items are enclosed in curly brackets { }.
a. List
b. Set 
c. String
d. None of the above

Show Answer ⟶
b. Set

41. ________ data type cannot have duplicate entries.
a. List
b. Set 
c. String
d. None of the above

Show Answer ⟶
b. Set

42. None is a special data type with a single value. It is used to signify the absence of value in a situation.
a. List
b. Set
c. String
d. None 

Show Answer ⟶
d. None

43. ___________ in Python holds data items in key-value pairs.
a. Dictionary 
b. Set
c. String
d. None

Show Answer ⟶
a. Dictionary

44. Items in a dictionary are enclosed in __________.
a. Parenthesis ()
b. Brackets []
c. Curly brackets {} 
d. All of the above

Show Answer ⟶
c. Curly brackets {}

45. In the dictionary every key is separated from its value using a _________.
a. Colon (:) 
b. Semicolon (;)
c. Comma (,)
d. All of the above

Show Answer ⟶
a. Colon (:)

46. Variables whose values can be changed after they are created and assigned are called __________.
a. Immutable
b. Mutable 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Mutable

47. Variables whose values cannot be changed after they are created and assigned are called _________.
a. Immutable 
b. Mutable
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Immutable

48. When we need uniqueness of elements and to avoid duplicacy it is preferable to use __________.
a. List
b. Set 
c. Tuple
d. All of the above

Show Answer ⟶
b. Set

49.The values that the operators work on are called __________.
a. Operands 
b. Assignment
c. Mathematical Operator
d. All of the above

Show Answer ⟶
a. Operands

50. ____________ that are used to perform the four basic arithmetic operations as well as modular division, floor division and exponentiation.
a. Arithmetic Operator 
b. Logical Operator
c. Relational Operator
d. All of the above

Show Answer ⟶
a. Arithmetic Operator

51. __________ calculation on operands. That is, raise the operand on the left to the power of the operand on the right.
a. Floor Division (//)
b. Exponent (**) 
c. Modulus (%)
d. None of the above

Show Answer ⟶
b. Exponent (**)

52. _____________ compares the values of the operands on either side and determines the relationship among them.
a. Arithmetic Operator
b. Logical Operator
c. Relational Operator 
d. All of the above

Show Answer ⟶
c. Relational Operator

53. _________ assigns or changes the value of the variable on its left.
a. Relational Operator
b. Assignment Operator 
c. Logical Operator
d. All of the above

Show Answer ⟶
b. Assignment Operator

54. Which one of the following logical operators is supported by python.
a. and
b. or
c. not
d. All of the above 

Show Answer ⟶
d. All of the above

55. _________ operator is used to check both the operands are true.
a. and 
b. or
c. not
d. All of the above

Show Answer ⟶
a. and

56. ___________ are used to determine whether the value of a variable is of a certain type or not.
a. Relational Operator
b. Logical Operator
c. Identity Operator 
d. All of the above

Show Answer ⟶
c. Identity Operator

57. ___________ can also be used to determine whether two variables are referring to the same object or not.
a. Relational Operator
b. Logical Operator
c. Identity Operator 
d. All of the above

Show Answer ⟶
c. Identity Operator

58. Membership operators are used to check if a value is a member of the given sequence or not.
a. Identity Operator
b. Membership Operators 
c. Relational Operators
d. All of the above

Show Answer ⟶
b. Membership Operators

59. An __________ is defined as a combination of constants, variables, and operators.
a. Expressions 
b. Precedence
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Expressions

60. Evaluation of the expression is based on __________ of operators.
a. Expressions
b. Precedence 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Precedence

61. Example of membership operators.
a. in
b. not
c. in
d. All of the above 

Show Answer ⟶
d. All of the above

62. Example of identity operators.
a. is
b. is not
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

63. In Python, we have the ____________ function for taking the user input.
a. prompt()
b. input() 
c. in()
d. None of the above

Show Answer ⟶
b. input()

64. In Python, we have the ___________ function for displaying the output.
a. prompt()
b. output()
c. print() 
d. None of the above

Show Answer ⟶
c. print()

65. ____________, also called type casting, happens when data type conversion takes place because the programmer forced it in the program.
a. Explicit conversion 
b. Implicit conversion
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Explicit conversion

66. __________, also known as coercion, happens when data type conversion is done automatically by Python and is not instructed by the programmer.
a. Explicit conversion
b. Implicit conversion 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Implicit conversion

67. A programmer can make mistakes while writing a program, and hence, the program may not execute or may generate wrong output. The process of identifying and removing such mistakes, also known as __________.
a. Bugs
b. Errors
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

68. Identifying and removing bugs or errors from the program is also known as __________.
a. Debugging 
b. Mistakes
c. Error
d. None of the above

Show Answer ⟶
a. Debugging

69. Which of the following errors occur in python programs.
a. Syntax error
b. Logical error
c. Runtime error
d. All of the above 

Show Answer ⟶
d. All of the above

70. A _________ produces an undesired output but without abrupt termination of the execution of the program.
a. Syntax error
b. Logical error 
c. Runtime error
d. All of the above

Show Answer ⟶
b. Logical error

71. A ___________ causes abnormal termination of the program while it is executing.
a. Syntax error
b. Logical error
c. Runtime error 
d. All of the above

Show Answer ⟶
c. Runtime error

72. Python is __________ language that can be used for a multitude of scientific and non-scientific computing purposes.
a. Open – source
b. High level
c. Interpreter – based
d. All of the above 

Show Answer ⟶
d. All of the above

73. Comments are __________ statements in a program.
a. Non – executable 
b. Executable
c. Both a) and b)
d. None of the above

Show Answer ⟶
a. Non – executable

74. __________ is a user defined name given to a variable or a constant in a program.
a. Keyword
b. Identifier 
c. Data type
d. All of the above

Show Answer ⟶
b. Identifier

75. The process of identifying and removing errors from a computer program is called _______.
a. Debugging 
b. Mistakes
c. Error
d. None of the above

Show Answer ⟶
a. Debugging

76. The order of execution of the statements in a program is known as _______.
a. Flow of control
b. Flow of structure
c. Flow of chart
d. None of the above

Show Answer ⟶
a. Flow of control

77. Python supports ____________ control structures.
a. Selection
b. Repetition
c. Both a) and b)
d. None of the above

Show Answer ⟶
c. Both a) and b)

78. Which one is the correct syntax of if statement in python.
a. if condition: 
statement(s)
b. if condition
statement(s)
a. if (condition)
statement(s)
a. if condition then
statement(s)

Show Answer ⟶
a. if condition: statement(s)

79. Number of ________ is dependent on the number of conditions to be checked. If the first condition is false, then the next condition is checked, and so on.
a. Elese if
b. If Else
c. Elif 
d. All of the above

Show Answer ⟶
c. Elif

80. The statements within a block are put inside __________.
a. Single quotes
b. Double quotes
c. Curly brackets 
d. Square brackets

Show Answer ⟶
c. Curly brackets

81. Leading whitespace (spaces and tabs) at the beginning of a statement is called ________.
a. Indentation 
b. Repetition
c. Code
d. None of the above

Show Answer ⟶
a. Indentation

82. This kind of repetition is also called __________ .
a. Indentation
b. Iteration 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Iteration

83. _________ constructs provide the facility to execute a set of statements in a program repetitively, based on a condition.
a. Conditional Statement
b. Looping Statement 
c. Both a) and b)
d. None of the above

Show Answer ⟶
b. Looping Statement

84. The statements in a loop are executed again and again as long as particular logical condition remains true.
a. For loop
b. While loop
c. Do-while loop
d. All of the above 

Show Answer ⟶
d. All of the above

85. What will happen when condition becomes false in the loop.
a. Loop Execute
b. Loop Terminates 
c. Loop Repeat once again
d. All of the above

Show Answer ⟶
b. Loop Terminates

86. What keyword would you add to an if statement to add a different condition?
a. Else if
b. Ifelse
c. elif 
d. None of the above

Show Answer ⟶
c. elif

87. What is the output of the given below program?
if 4 + 2 == 8:
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True
b. Condition is False
c. No Output
d. Error

Show Answer ⟶
b. Condition is False

88. What is the output of the given below program?
if 4 + 2 == 8:
print(“Condition is True”)
else:
print(“Condition is False”)
print(“Welcome”)

a. Condition is True
b. Condition is False 
Welcome
c. Condition is True
Welcome
d. Error

Show Answer ⟶
Condition is False Welcome

89. Find the output of the given Python program?
a = 50
b = 60
if a < 50:
print(“Condition is True”)
if b <= 60:
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True 
b. Condition is False
c. No Output
d. Error

Show Answer ⟶
a. Condition is True

90. What is the output of the given below program?
a = 35
if a >= 35:
print(“Condition is True”)
if a <= 35:
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True
b. Condition is True 
Condition is True
c. Condition is True
Condition is False
d. Condition is False
Condition is True

Show Answer ⟶
b. Condition is True Condition is True

91. Find the output of the given Python program?
a, b, c = 1, 2, 3
if a > 0:
if b < 2:
print(“Welcome”)
elif c >= 3:
print(“Welcome to my School”)
else:
print(“New School”)

a. Welcome
b. Welcome to my School 
c. New School
d. Run time error

Show Answer ⟶
b. Welcome to my School

92. Find the output of the given Python program?
a, b, c = 1, 2, 3
if a + b + c:
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True 
b. Condition is False
c. No Output
d. Runt time error

Show Answer ⟶
a. Condition is True

93. What is the output of the given below program?
b = 5
if a < b:
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True
b. Condition is False
c. NameError: name ‘a’ is not defined 
d. No Output

Show Answer ⟶
c. NameError: name ‘a’ is not defined

94. What is the output of the given below program?
a = b = true
if (a and b):
print(“Condition is True”)
else:
print(“Condition is False”)

a. Condition is True
b. Condition is False
c. NameError: name ‘true’ is not defined 
d. No Output

Show Answer ⟶
c. NameError: name ‘true’ is not defined

95. Which of the following is not a Python loop?
a. for loop
b. do-while loop 
c. while loop
d. None of the above

Show Answer ⟶
b. do-while loop

96. Regarding Python loops, which of the following statements is false?
a. Loops are utilized to repeat specific actions.
b. When several statements need to be performed repeatedly until the specified condition turns false, the while loop is employed. 
c. When several statements need to be run repeatedly until the provided condition is true, a while loop is employed.
d. List elements can be repeated through using a for loop.

Show Answer ⟶
b. When several statements need to be performed repeatedly until the specified condition turns false, the while loop is employed.

97. What does range() function returns ?
a. list of numbers.
b. integer object.
c. range object. 
d. None of the above

Show Answer ⟶
c. range object.

98. Which of the following statements about Python loops is True?
a. The keyword “end” should be used to end loops.
b. The components of strings cannot be repeated over using a loop.
c. You can break control from the current loop by using the keyword “break.” 
d. To continue with the remaining statements inside the loop, use the keyword “continue.”

Show Answer ⟶
c. You can break control from the current loop by using the keyword “break.”

99. What will be the output of given Python code?
a=7
b=0
while(a):
if(a>5):
b=b+a-2
a=a-1
else:
break
print(a)
print(b)

a. 4 7
b. 5 9 
c. 4 10
d. 5 3

Show Answer ⟶
b. 5 9

100. Which of the following is a valid for loop in Python?
a. for i in range(5,5)
b. for i in range(0,5)
c. for i in range(0,5): 
d. for i in range(5)

Show Answer ⟶
c. for i in range(0,5):

101. What will be the output of given Python code?
str=”Welcome”
sum=0
for n in str:
if(n!=”l”):
sum=sum+1
else:
pass
print(sum)

a. 5
b. 6 
c. 4
d. 9

Show Answer ⟶
b. 6

102. How many times will the loop run?
i=5
while(i>0):
i=i-1
print (i)

a. 5 
b. 4
c. 3
d. 2

Show Answer ⟶
a. 5

103. What will be the output of the following code?
x = 12
for i in x:
print(i)

a. 12
b. 1 2
c. Error 
d. None of the above

Show Answer ⟶
c. Error

104. One loop may be used inside another loop using the Python programming language, which is known as?
a. switch
b. foreach
c. nested 
d. forall

Show Answer ⟶
c. nested

105. Which of the following loop is work on the particular range in python ?
a. while loop
b. for loop 
c. do while loop
d. None of the above

Show Answer ⟶
b. for loop

106.What does break statement do?
a. Stop 
b. Repeat
c. Skip
d. Print

Show Answer ⟶
a. Stop

107. What does continue statement do?
a. Print
b. Stop
c. Skip 
d. Repeat

Show Answer ⟶
c. Skip

108. The if statement is used for _________.
a. Selection making
b. Decision making
c. Both a) and b)
d. None of the above

Show Answer ⟶
c. Both a) and b)

109. ___________ statement iterates over a range of values or a sequence.
a. For 
b. While
c. Do-While
d. None of the above

Show Answer ⟶
a. For

110. The statements within the body of the ________ must ensure that the condition eventually becomes false; otherwise, the loop will become an infinite loop, leading to a logical error in the program.
a. For loop
b. While loop 
c. Do-While loop
d. None of the above

Show Answer ⟶
b. While loop

111. The __________ statement immediately exits a loop, skipping the rest of the loop’s body. Execution continues with the statement immediately following the body of the loop.
a. Break 
b. Continue
c. Exit
d. None of the above

Show Answer ⟶
a. Break

112. When a _________ statement is encountered, the control jumps to the beginning of the loop for the next iteration.
a. Break
b. Continue 
c. Exit
d. None of the above

Show Answer ⟶
b. Continue

113. A loop contained within another loop is called a __________.
a. Another Loop
b. Nested Loop 
c. Next Loop
d. None of the above

Show Answer ⟶
b. Nested Loop

114. Python executes one statement to another statement from starting to end, this is known as ____________.
a. Selection construct
c. Sequential Construct 
b. Iteration Construct
d. All of the above

Show Answer ⟶
c. Sequential Construct

115. The sequence in which statements in a programme are executed is referred to as ___________.
a. Constant flow
c. Flow of control 
b. Selection flow
d. None of the above

Show Answer ⟶
c. Flow of control

116. There are _______ types of control structures that Python supports.
a. 4
b. 3
c. 2 
a. 1

Show Answer ⟶
c. 2

117. Which of the following is a Python control structure?
a. Iteration
b. Selection
c. Both a) and b) 
d. None of the above

Show Answer ⟶
c. Both a) and b)

118. With the use of a __________ statement, the idea of decision-making or selection is implemented in programming.
a. For loop
b. While loop
c. If & Else 
d. Break & Continue

Show Answer ⟶
c. If & Else

119. A program’s elif count depends on the _____________.
a. Dependent on the condition 
b. Dependent on the writing methods
c. Dependent on the loop
d. None of the above

Show Answer ⟶
a. Dependent on the condition

120. ________ is an empty statement in Python.
a. Fail
b. Pass 
c. Null
d. None of the above

Show Answer ⟶
b. Pass

121. There are ______ spaces of indentation around a statement inside of “if.”
a. 4 
b. 8
c. 16
d. 20

Show Answer ⟶
a. 4

122. If the condition is True, Amit wants to display “Welcome,” else “Welcome to my webpage” if the condition is false. Which of the following statements makes it easier to put this into practice?
a. For Statement
b. While Statement
c. If & Else Statement 
d. None of the above

Show Answer ⟶
c. If & Else Statement

123. In order to determine if a number is even or odd, Amit wants to develop a programme. He needs to have a solid understanding of _________ to do this.
a. Conditional Statement 
b. Break Statement
c. Continue Statement
d. None of the above

Show Answer ⟶
a. Conditional Statement

124. When if-elif statement is used in python?
a. Only one condition
b. Multiple condition 
c. Never used
d. None of the above

Show Answer ⟶
b. Multiple condition

125. What is the purpose of “else” statement?
a. It will execute when condition is false 
b. It will execute when condition is true
c. It will never execuite.
d. Both a) and b)

Show Answer ⟶
a. It will execute when condition is false

Python Revision Tour Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Python Revision Tour Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Python Revision Tour Class 12 Notes

Token in Python

The smallest unit in a Python programme is called a token. In python all the instructions and statements in a program are built with tokens. Different type of tokens in python are keywords, identifier, Literals/values, operators and punctuators –

Keywords

Words with a particular importance or meaning in a programming language are known as keywords. They are utilised for their unique qualities. There are 33 keywords in Python True, False, class, break, continue, and, as, try, while, for, or, not, if, elif, print, etc.

Identifiers

The names assigned to any variable, function, class, list, method, etc. for their identification are known as identifiers. Python has certain guidelines for naming identifiers and is a case-sensitive language. To name an identifier, follow these guidelines: –

  1. Code in python is case – sensitive
  2. Always identifier starts with capital letter(A – Z), small letter (a – z) or an underscore( _ ).
  3. Digits are not allowed to define in first character but you can use between.
  4. No whitespace or special characters are allowed.
  5. No keyword is allowed to define identifier.

Literals or Values

In Python, literals are the raw data that is assigned to variables or constants during programming. There are five different types of literals string literals, numeric literals, Boolean literals and special literals none.

a) String literals

The string literals in Python are represented by text enclosed in single, double, or triple quotations. Examples include “Computer Science,” ‘Computer Science’, ”’Computer Science”’ etc.
Note – Triple quotes string is used to write multiple line.
Example –
n1 = ‘Computer Science’
n2 = “Computer Science”
n3 = ”’Computer Science”’
print(n1)
print(n2)
print(n3)

b) Numeric Literals

Literals that have been use to storing numbers is known is Numeric Literals. There are basicaly three numerical literals –

  1. Integer Literal
  2. Float Literal
  3. Complex Literal

Example
num1 = 10
num2 = 15.5
num3 = -20
print(num1)
print(num2)
print(num3)

c) Boolean Literal

Boolean literals have only two values True of False.
Example
num = (4 == 4)
print(num)

d) Special literals none

The special literal “None” in Python used to signify no values, the absence of values, or nothingness.
Example
str = None
print(str)

Operators

In Python, operators are specialized symbols that perform arithmetic or logical operations. The operation in the variable are applied using operands.

The operators can be arithmetic operators(+, -, * /, %, **, //), bitwise operators (&, ^, |), shift operators (<<, >>), identity operators(is, is not), relational operators(>, <, >=, <=, ==, !=), logical operators (and, or), assignment operator ( = ), membership operators (in, not in), arithmetic-assignment operators (/=, +=, -=, %=, **=, //=).

Punctuators

The structures, statements, and expressions in Python are organized using these symbols known as punctuators. Several punctuators are in python [ ] { } ( ) @ -= += *= //= **== = , etc.

Barebones of a python program

a) Expressions – An expression is a set of operators and operands that together produce a unique value when interpreted.

b) Statements – Which are programming instructions or pieces of code that a Python interpreter can carry out.

c) Comments – Python comments start with the hash symbol # and continue to the end of the line. Comments can be single line comments and multi-line comments.

d) Functions – A function is a block of code that only executes when called. You can supply parameters—data—to a function. As a result, a function may return data.

e) Block or suit – In Python, a set of discrete statements that together form a single code block are referred to as suites. All statements inside a block or suite are indented at the same level.

Variables and Assignments

A symbolic name that serves as a reference or pointer to an object is called a variable in Python. You can use the variable name to refer to an object once it has been assigned to it. However, the object itself still holds the data.
Example
name = “Python”

Dynamic Type vs Static Type

The term “dynamic typing” refers to a variable’s type only being established during runtime. Whereas the statically type done at compile time in a python. Statically type of a variable cannot be change.

Multiple Assignments

Values are assigned by Python from right to left. You can assign numerous variables simultaneously in a single line of code using multiple assignment.
a) Assigning same value to multiple variables
n3 = n2 = n1 = 20
b) Assigning multiple values to multiple variables
n1, n2, n3 = 10, 20, 30

Simple input and output

Input 

Python automatically treats every input as a string input. To convert it to any other data type, we must explicitly convert the input. For this, we must utilize the int() and float() methods to convert the input to an int or a float, respectively.
example
name = input(‘What is your name’)
age = int(input(‘What is your age’)

Output

The print() method in Python allows users to display output on the screen. print statement automatically converts the items to strings.
example
num = 10
print(“Number is “)
print(num) # auto converted to string
print(34) # auto converted to string

Data Type

The classification or categorizing of data elements is known as data types. It represents the type of value that specifies the operations that can be carried out on a given set of data. In Python programming, everything is an object, hence variables and data types are both instances or objects.

Python has following data types by default.

Data types for Numbers

a) Integer – The integers represent by “int”. It contains positive or negative values.
b) Boolean – The boolean type store on True or False, behave like the value 0 and 1.
c) Floating – It is a real number with specified with decimal point.
d) Complex – Complex class is a representation of a complex number (real part) + (imaginary part)j. For example – 2+3j.

Data types for String

Strings in Python are collections of Unicode characters. A single, double, or triple quote are used to store string. There is no character data type in Python.
Example
name = ‘Computer Science’
name1 = “Computer Science’
name2 = ”’Computer Science”’

Lists

Lists are similar to arrays, it is a collections of data in an ordered way. list’s items don’t have to be of the same type in python.
Example
my_list = [1, 2, 3]
my_list1 = [“Computer”, “Science”, “Python”]
my_list2 = [“Computer Science”, 99]

Tuples

Tuple is similar to lists, It is also an ordered collection of python. The only difference between tuple and list is that tuples can’t be modified after it is created, So, that’s why it is known as immutable.
Example
my_tuple = (1, 2, 3)
my_tuple1 = (“Computer”, “Science”, “Python”)
my_tuple2 = (“Computer Science”, 99)

Dictionaries

In Python, a dictionary is an unordered collection of data values that can be used to store data values like a map. This dictionary can hold only single value as an element, Dictionary holds key:value pair.
Example
my_dict = (1: ‘Computer’, 2: ‘Mathematics’, 3: ‘Biology’)
my_dict = (‘Computer’: 1, ‘Mathematics’: 2, ‘Biology’: 3)

Mutable and Immutable Types

In Python, there are two different types of objects: mutable and immutable. It is possible to change mutable data types after they have been formed, whereas immutable objects cannot be altered once they have been created.

Mutable types

The mutable types are those whose values can be changed in place. Only three types are mutable in python lists, dictionaries and sets.

Immutable types

The immutable types are those that can never change their value in place. In Python, the following types are immutable in python integers, floating point numbers, Booleans, strings, tuples.

Expressions

In Python, an expression is made up of both operators and operands. example of expressions in python are num = num + 3 0, num = num + 40.
Operators in Python are specialised symbols that indicate that a particular type of computation should be carried out. Operands are the values that an operator manipulates. An expression is a collection of operators and operands, such as num = num + 3 0.

Type Casting (Explicit Type Conversion)

Type casting, often known as explicit type conversion, Users change the data type of an object to the required data type via explicit type conversion. To achieve explicit type conversion, we use predefined functions like int(), float(), str(), etc.

Math Library Functions

The Python standard library includes a built-in module called math that offers common mathematical functions.

  • math.ceil() – The ceil() function return the smallest integer.
  • math.sqrt() – The sqrt() function returns the square root of the value.
  • math.exp() – The exp() function returns the natural logarithm reised to the power.
  • math.fabs() – The fabs() function returns the absolute value.
  • math.floor() – The floor() function returns round a number down to the nearest intger.
  • math.log() – The log() function is used to calculate the natural logarithmic value.
  • math.pow() – The pow() function returns base raised to exp power.
  • math.sin() – The sin() function returns sine of a number.
  • math.cos() – The cos() function return the cosine of the value.
  • math.tan() – The tan() function return the tangent of the value.
  • math.degrees() – The degrees() converts angle of value from degrees to radians.

Statement Flow Control

Control flow refers to the sequence in which a program’s code is executed. Conditions, loops, and function calls all play a role in how a Python programme is controlled.
Python has three types of control structures –
a) Sequential – By default mode
b) Selection – Used in decision making like if, swithc etc.
c) Repetition – It is used in looping or repeating a code multiple times

Compound Statement

Compound statements include other statements (or sets of statements), and they modify or direct how those other statements are executed. Compound statements often take up numerous lines, however in some cases, a complete compound statement can fit on a single line.
Example
<compound statement header> :
<indented body containing multiple simple and/ or compound statement>

The IF & IF-ELSE conditionals

When using the if statement in Python, a Boolean expression is evaluated to determine whether it is true or false. If the condition is true, the statement inside the if block is executed. If the condition is false, the statement inside the else block is only executed if you have written the else block; otherwise, nothing happens.
Syntax of IF condition
if <conditional expression> :
     statement
     [statement]

Syntax of IF-ELSE condition
if <conditional expression> :
     statement
     [statement]
else :
     statement
     [statement]

Nested IF statement

One IF function contains one test, with TRUE or FALSE as the two possible results. You can test numerous criteria and expand the number of outcomes by using nested IF functions, which are one IF function inside of another.
Syntax of Nested IF statement
if condition :
     if condition :
          Statement
     else :
          Statement

Looping Statement

In Python, looping statements are used to run a block of statements or code continuously for as many times as the user specifies. Python offers us two different forms of loops for loop and while loop.

The For loop

Python’s for loop is made to go over each element of any sequence, such a list or a string, one by one.
Syntax of FOR loop –
for <variable> in <sequence> :
     statements_to_repeat

The range() based for loop

The range() function allows us to cycle across a set of code a predetermined number of times. The range() function returns a series of numbers and, by default, starts at 0 and increments by 1 before stopping at a predetermined value.
Syntax –
range(stop)
range(start, stop)
range(start, stop, step)

The While loop

A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remain true.
Syntax –
while <logical expression> :
loop-body

JUMP Statemement – break and condinue

Python offers two jump statement – break and continue – to be used within loops to jump out of loop-iterations.

The break Statement

A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.
Syntax –
break

Example –
a = b = c = 0
for i in range(1, 11) :
     a = int(input(“Enter number 1 :”))
     b = int(input(“Enter number 2 :))
     if b == 0 :
          print(“Division by zero error! Aborting”)
          break
     else
          c=a/b
          print(“Quotient = “, c)
print(“program over!”)

The continue statement

Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
Syntax –
continue

Loop else statement

Python supports combining the else keyword with both the for and while loops. After the body of the loop, the else block is displayed. After each iteration, the statements in the else block will be carried out. Only when the else block has been run does the programme break from the loop.
Syntax –
for <variable> in <sequence> :
     statement1
     statement2
else :
     statement(s)

while <test condition> :
     statement1
     statement2
else :
     statement(s)

Nested Loops

A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop.
The following is an example of a nested loop :
for i in range(1,6) :
     for j in range(1, i) :
          print(“*”, end =’ ‘)

String in Python

Strings in Python are collections of bytes that represent Unicode characters. A single character in Python is just a string of length 1, since there is no such thing as a character data type. Python stores strings as individual characters in consecutive locations with a two-way index. In Python, single, double, or even triple quotes can be used to store strings.
Example
1. string1 = ‘Welcome’
2. string1 = “Welcome”
3. strong1 = ”’Welcome”’

One important thing about string is that you cannot change the individual letters of a string by assignment because strings are immutable.

Traversing a String

When you traverse a string, you use the subscript to access each element of the string one after the other because all the characters are stored in sequence. You can iterate over a string using a for or while loop.
Example
string1 = “Welcome”
string1[0]=’W’, string1[1]=’e’, string1[2]=’l’, string1[3]=’c’, string1[4]=’o’, string1[5]=’m’, string1[6]=’e’

String Operators

There are various operators that can be used to manipulate strings in multiple ways.

>>String Concatenation Operator +

The + operator create a new string by joining the two operand string.
Example
string1 = “Welcome” + “to my School”

>>String Replication Operator *

The string replication operator, *, repeats a single string as many times as you wish through the integer you supply when just one string and one integer are utilized. With string replication, we can duplicate a single string value an equivalent number of times as an integer.
Example
print(“Hello”*3)

output
print(“Hello”*3)

>>Membership Operators

There are two membership operators for strings. These are “in” and “not in”.

a) in – return True if a character or a substring exists in the given string; False otherwise

Example 
print(“a” in “amit”)

Output
True

b) not in – returns True if a character or a substring does not exist in the given string; False otherwise

Example 
print(“a” not in “amit”)

Output
False

Both membership operators, require that both operands used with them are of string type.

>>Comparison Operators

Operators that compare values and return true or false are known as comparison operators. These are the operators: >,, >=, =, ===, and!==.
Example
a) print(2>3)

Output
False

b) print(2>=3)

Output
False

c) print(2<3)

Output
True

d) print(2<=3)

Output
True

e) print(2==3)

Output
False

f) print(2!=3)

Output
True

String Slices

The term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. Python involves doing so from start to end in order to create a sub-string from the given text.

Example
string1 = “Welcome”
print(string1[2:5])

Output
lco

String Functions

There are numerous built-in functions and strategies for manipulating strings in Python. The following syntax can be used to apply the string manipulation techniques that are discussed below to strings –
Syntax –
<stringobject>.<method name>()

a) string.capitalize() – Return a copy of the string with its first character capitalized.
Example
print(‘welcome to my school’.capitalize())

Output
Welcome to my school

b) string.find(sub,start,end) – Returns the lowest index in the string where the substring sub is found within the slice range of start and end. Retruns -1 if sub is not found.
Example
1) string1 = “Welcome to my School”
x = string1.find(“School”)
print(x)

Output
14

2) string1 = “Welcome to my School”
x = string1.find(“my”, 3, 20)
print(x)

Output
11

c) string.isalnum() – Returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is al least on character, False otherwise.
Example
string1 = “Welcome1”
x = string1.isalnum()
print(x)

Output
True

d) string.isalpha() – Returns True if all characters in the string are alphabetc and there is at least one characters, False otherwise.
Example
string1 = “Welcome”
x = string1.isalpha()
print(x)

Output
True

e) string.isdigit() – Returns True if all the characters in the string are digits. There must be at least one digit, otherwise it returns False.
Example
string1 = “3652”
x = string1.isdigit()
print(x)

Output
True

f) string.isspace() – Returns True if there will only one whitespace characters in the string.

Example
string1 = ” “
x = string1.isspace()
print(x)

Output
True

g) string.islower() – Returns True if all cased characters in the string are lowercase. There must be at least one cased character. It returns False otherwise.
Example
string1 = “welcome”
x = string1.islower()
print(x)

Output
True

h) string.isupper() – Test whether all cased characters in the string are uppercase and requires that there be at least one cased character. Returns True if so and False otherwise.
Example
string1 = “WELCOME”
x = string1.isupper()
print(x)

Output
True

i) string.lower() – Returns a copy of the string converted to lowercase.
Example
string1 = “WELCOME”
x = string1.lower()
print(x)

Output
welcome

j) string.upper() – Returns a copy of the string converted to uppercase.
Example
string1 = “welcome”
x = string1.upper()
print(x)

Output
WELCOME

h) string.lstrip([chars]) – Returns a copy of the string with leading characters removed.
Example
string1 = “Welcome”
x = string1.lstrip(‘Wel’)
print(x)

Output
come

i) string.rstrip([chars]) – Return a copy of the string with trailing characters removed.
Example
string1 = “Welcome”
x = string1.rstrip(‘come’)
print(x)

Output
wel

Lists in Python

A list is a common Python data type that may hold a series of values of any type. Square brackets are used to indicate the lists. lists are mutable.
Exmple
a. [] # list with no member, empty list
b. [1, 2, 3] # list of integers
c. [1, 2.5, 3.4, 2] # list of numbers(integers and floating point)
d. [‘a’, ‘b’, ‘c’] # list of characters
e. [‘a’, 1, ‘b’, 3.2, ‘New’] # list of mixed value types
f. [‘One’, ‘Two’, ‘Three’] # list of strings

Create lists

To create a list, put a number of expressions, separated by commas in square brackets.
Example
my_list = []
my_list = [33, 32, 54]

Create Empty list

The empty list is [ ]. you can also create an empty list as –
Example
my_list = list()

Create list from existing sequences

You can also use the built – in list type object to create lists from sequences as per the syntax given below –
Example
my_list = list(“Welcome”)
print(my_list)

Output
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

Creating list from keyboard input

You can use this method for creating lists of single characters or single digits via keyboard input.
Example
my_list = list(input(“Enter you name”))
print(my_list)

Output
Enter you name Welcome
Welcome
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

List vs String

Python defines a string as an organised collection of characters. A list is an ordered sequence of different object kinds, whereas a string is an ordered sequence of letters. This is important to keep in mind.

Difference between lists and string

a. Storage – Lists are stored in memory exactly like strings, except that because some of their objects are larger than others, they store a reference at each index insted of single character as in strings.

b. Mutability – Strings are not mutable, while lists are mutable. You cannot individual elements of a string in place, but lists allow you to do so. That is following statement is fully valid for lists.

List Operations

a. Traversing a list – Traversing a list means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a list, as per following syntax –
Example
my_list = [‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]
for a in my_list :
print(a)

Output
W
e
l
c
o
m
e

Joining lists

The concatenation operator + is used to joins two different lists and return the concatenated list.
Example
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
print(my_list1 + my_list2)

Output
[1, 2, 3, 4, 5, 6]

Repeating or Replicating lists

Like strings, you can use * operator to replicate a list specified number of times.
Example
my_list = [1, 2, 3]
print(my_list * 3)

Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Slicing the lists

List slicing, like string slices are the sub part of a list extracted out. you can use indexes of list elements to create list slices as per following format –
Example
my_list = [15, 33, 25, 14, 72, 52, 65, 47, 95]
print(my_list[3: -3])

Output
[14, 72, 52]

List manipulation

You can perform various operations on lists like, appending, updating, deleting etc.

Appending elements to a list

You can add items to an existing list. The append() method adds a single item to the end of the list.
Example
my_list = [10, 12, 14]
my_list.append(22)
print(my_list)

Output
[10, 12, 14, 22]

Updating Elements to a list

To update or change an element of the list in place, you just have to assign new value to the element’s index in list as per syntax –
Example
my_list = [10, 12, 14]
my_list[1] = 22
print(my_list)

Output
[10, 22, 14]

Deleting Elements from a list

You can also remove items from lists. The del statement can be used to remove an individual item, or to remove all items identified by a slice.
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
del my_list[2]
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

Making True copy of a list

Assignment with an assignment operator ( = ) on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory (called shallow copy).
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = list(my_list)
print(new_list)

Output
[10, 12, 14, 16, 18, 20, 22]

The index method

The function returns the index of first matched item from the list.

Example
my_list = [10, 12, 14, 16, 18, 20, 22]
print(my_list.index(14))

Output
2

The extend method

The extend() method is also used for adding multiple elements to a list. The extend() function works as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = [24, 26, 28, 30]
my_list.extend(new_list)
print(my_list)

Output
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]

The insert method

The insert() function inserts an item at a given position. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.insert(3, 44)
print(my_list)

Output
[10, 12, 14, 44, 16, 18, 20, 22]

The pop method

The pop() is used to remove the item from the list. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.pop(3)
print(my_list)

Output
[10, 12, 14, 18, 20, 22]

The remove method

The remove() method removes the first occurrence of given item from the list. It is used as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.remove(14)
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

The clear method

The method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.clear()
print(my_list)

Output
[]

The count method

This function returns the count of the item that you passed as argument. If the given item is not in the list, It will return zero.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
print(my_list.count(12))

Output
2

The reverse method

The reverse() reverses the items of the list. This is done “in place”, it does not create a new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.reverse()
print(my_list)

Output
[22, 12, 18, 16, 14, 12, 10]

The sort method

The sort() function sorts the items of the list, by default in increasing order. This is done “in place”, it does not create new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.sort()
print(my_list)

Output
[10, 12, 12, 14, 16, 18, 22]

Tuples in Python

The Tuples are depicted through parentheses, round brackets, following are some tuples in Python.
Example
a. () # tuple with no member, empty list
b. (1, ) # tuple with one member
c. (1, 2.5, 3.4, 2) # tuple of numbers(integers and floating point)
d. (‘a’, ‘b’, ‘c’) # tuple of characters
e. (‘a’, 1, ‘b’, 3.2, ‘New’) # tuple of mixed value types
f. (‘One’, ‘Two’, ‘Three’) # tuple of strings

Creating Tuples

To create a tuple, put a number of expressions, separated by commas in parentheses. That is, to create a tuple you can write in the form given below –
Example
my_tuple = tuple(“Welcome”)

Creating Empty Tuple

The empty tuple is (). you can also create an empty tuple as –
my_list = tuple()

Create Single Element Tuple

Making a tuple with a single element is tricky because if you just give a single element in round brackets.
Example
my_tuple = (1)

Creating Tuple from keyboard input

You can use this method of creating tuples of single characters or single digits via keyboard input.
Example
my_tuple = tuple(input(“Enter tuple elements “))
print(my_tuple)

Output
Enter tuple elements Welcome
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Difference between Tuples and Lists

Lists are mutable, while tuples are not. A tuple’s elements cannot be changed individually once they are in place, while lists let you do so.

Traversing a Tuple

Accessing and processing each element of a tuple is known as traversing it. It is simple to traverse or loop over the items in a tuple when using the for loop.
Example
my_tuple = (“Welcome”, “to”, “my”, “School”)
for a in my_tuple :
print(a)

Output
Welcome
to
my
School

Joining Tuples

The + operator used to join two different tuples.
Example
my_tuple1 = (1, 2, 3)
my_tuple2 = (4, 5, 6)
print(my_tuple1 + my_tuple2)

Output
(1, 2, 3, 4, 5, 6)

Repeating or Replicating Tuples

Like strings and lists, you can use * operator to replicate a tuple specified number of times.
Example
my_tuple = (1, 2, 3)
print(my_tuple * 3)

Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Slicing the tuples

Tuple slices, like list-slices or string slices are the sub part of the tuple extracted out. you can use indexes of tuple elements to create tuple slices as per following format –
Example
my_tuple = (1, 2, 3, 4, 5, 6)
new_tuple = my_tuple[ 2 : -2]
print(new_tuple)

Output
(3, 4)

Tuple Functions and Methods

1. The len() method – This method is used to find the length of the tuple.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(len(my_tuple))

Output
6

2. The max() method – This method is used to find the maximum value in the given tuples.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(max(my_tuple))

Output
6

3. The min() method – This method is used to find the minimum value in the given tuples.
my_tuple = (1, 2, 3, 4, 5, 6)
print(min(my_tuple))

Output
1

4. The index() method – It returns the index of an existing element of a tuple.
Example
my_tuple = (1, 2, 3, 4, 5, 6)
print(my_tuple.index(4))

Output
3

5. The count() function – The count() function returns the number of count memeber element in the given tuples.
Example
my_tuple = (1, 2, 3, 4, 5, 4)
print(my_tuple.count(4))

Output
2

6. The tuple() method – This method is actually constructor method that can be used to create tuples from different types of values.
Example
my_tuple = tuple(“Welcome”)
print(my_tuple)

Output
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Dictionaries in Python

A group of key-value pairs are assembled in dictionaries written in Python. Dictionary elements have the form of key:value pairs that link keys to values, making dictionaries mutable, unordered collections. To create a dictionary, you need to include the key:value pairs in curly braces as per following syntax –
Example
my_dict = {1:”One”, 2:”Two”, 3:”Three”}

Accessing Elements of a Dictionary

In dictionaries, the keys listed in the key are used to access the elements: value pairs according to the syntax displayed below –
Example
my_dict = {1: “One”, 2: “Two”, 3: “Three”}
print(my_dict[2])

Output
Two

Traversing a Dictionary

Accessing and handling each element in a collection is known as traversal. A dictionary’s elements can be easily traversed or repeated over with the help of the for loop.
Example
my_dict = { ‘Gujarat’: ‘Gandhinagar’, ‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}
keys = my_dict.keys()
print(keys)

Output
dict_keys([‘Gujarat’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

Adding Elements to Dictionary

We can add new elements to a dictionary using assignment operator. But remember the key being added must not exist in dictionary and must be unique.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict[‘Dept’] = ‘Sales’
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000, ‘Age’: 28, ‘Dept’: ‘Sales’}

Deleting Elements from a Dictionary

There are two different methods are used for deleting elements from a dictionary –
a) To delete the element from the dictionary you can use del command.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
del my_dict[‘Age’]
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

b) Another method to delete elements from a dictionary is pop() method.
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict.pop(‘Age’)
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

Dictionary Functions and Methods

a. The len() method – This method returns length of the dictionary, the count of elements in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(len(my_dict))

Output
3

b. The clear() method – The method removes all items from the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.clear())

Output
None

c. The get() method – Using get() method you can get the item with the given key.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.get(‘Name’))

Output
Amit

d. The items() method – This method returns all the items in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.items())

Output
dict_items([(‘Name’, ‘Amit’), (‘Salary’, 30000), (‘Age’, 28)])

e. The key() method – This method returns all of the keys in the dictionary as a sequence of keys.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.keys())

Output
dict_keys([‘Name’, ‘Salary’, ‘Age’])

f. The values() method – The method returns all the values from the dictionary as a sequence.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.values())

Output
dict_values([‘Amit’, 30000, 28])

g. The update() method – This method merges key:value pairs from the new dictionary into the original dictionary.
Example
emp1 = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
emp2 = {‘Name’ : ‘Rejesh’, ‘Salary’ : 35000, ‘Age’ : 29}
emp1.update(emp2)
print(emp1)

Output
{‘Name’: ‘Rejesh’, ‘Salary’: 35000, ‘Age’: 29}

Python Revision Tour 2 Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Python Revision Tour 2 Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Python Revision Tour 2 Class 12 Notes

String in Python

Strings in Python are collections of bytes that represent Unicode characters. A single character in Python is just a string of length 1, since there is no such thing as a character data type. Python stores strings as individual characters in consecutive locations with a two-way index. In Python, single, double, or even triple quotes can be used to store strings.
Example
1. string1 = ‘Welcome’
2. string1 = “Welcome”
3. strong1 = ”’Welcome”’

One important thing about string is that you cannot change the individual letters of a string by assignment because strings are immutable.

Traversing a String

When you traverse a string, you use the subscript to access each element of the string one after the other because all the characters are stored in sequence. You can iterate over a string using a for or while loop.
Example
string1 = “Welcome”
string1[0]=’W’, string1[1]=’e’, string1[2]=’l’, string1[3]=’c’, string1[4]=’o’, string1[5]=’m’, string1[6]=’e’

String Operators

There are various operators that can be used to manipulate strings in multiple ways.

>>String Concatenation Operator +

The + operator create a new string by joining the two operand string.
Example
string1 = “Welcome” + “to my School”

>>String Replication Operator *

The string replication operator, *, repeats a single string as many times as you wish through the integer you supply when just one string and one integer are utilized. With string replication, we can duplicate a single string value an equivalent number of times as an integer.
Example
print(“Hello”*3)

output
print(“Hello”*3)

>>Membership Operators

There are two membership operators for strings. These are “in” and “not in”.

a) in – return True if a character or a substring exists in the given string; False otherwise

Example 
print(“a” in “amit”)

Output
True

b) not in – returns True if a character or a substring does not exist in the given string; False otherwise

Example 
print(“a” not in “amit”)

Output
False

Both membership operators, require that both operands used with them are of string type.

>>Comparison Operators

Operators that compare values and return true or false are known as comparison operators. These are the operators: >,, >=, =, ===, and!==.
Example
a) print(2>3)

Output
False

b) print(2>=3)

Output
False

c) print(2<3)

Output
True

d) print(2<=3)

Output
True

e) print(2==3)

Output
False

f) print(2!=3)

Output
True

String Slices

The term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. Python involves doing so from start to end in order to create a sub-string from the given text.

Example
string1 = “Welcome”
print(string1[2:5])

Output
lco

String Functions

There are numerous built-in functions and strategies for manipulating strings in Python. The following syntax can be used to apply the string manipulation techniques that are discussed below to strings –
Syntax –
<stringobject>.<method name>()

a) string.capitalize() – Return a copy of the string with its first character capitalized.
Example
print(‘welcome to my school’.capitalize())

Output
Welcome to my school

b) string.find(sub,start,end) – Returns the lowest index in the string where the substring sub is found within the slice range of start and end. Retruns -1 if sub is not found.
Example
1) string1 = “Welcome to my School”
x = string1.find(“School”)
print(x)

Output
14

2) string1 = “Welcome to my School”
x = string1.find(“my”, 3, 20)
print(x)

Output
11

c) string.isalnum() – Returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is al least on character, False otherwise.
Example
string1 = “Welcome1”
x = string1.isalnum()
print(x)

Output
True

d) string.isalpha() – Returns True if all characters in the string are alphabetc and there is at least one characters, False otherwise.
Example
string1 = “Welcome”
x = string1.isalpha()
print(x)

Output
True

e) string.isdigit() – Returns True if all the characters in the string are digits. There must be at least one digit, otherwise it returns False.
Example
string1 = “3652”
x = string1.isdigit()
print(x)

Output
True

f) string.isspace() – Returns True if there will only one whitespace characters in the string.

Example
string1 = ” “
x = string1.isspace()
print(x)

Output
True

g) string.islower() – Returns True if all cased characters in the string are lowercase. There must be at least one cased character. It returns False otherwise.
Example
string1 = “welcome”
x = string1.islower()
print(x)

Output
True

h) string.isupper() – Test whether all cased characters in the string are uppercase and requires that there be at least one cased character. Returns True if so and False otherwise.
Example
string1 = “WELCOME”
x = string1.isupper()
print(x)

Output
True

i) string.lower() – Returns a copy of the string converted to lowercase.
Example
string1 = “WELCOME”
x = string1.lower()
print(x)

Output
welcome

j) string.upper() – Returns a copy of the string converted to uppercase.
Example
string1 = “welcome”
x = string1.upper()
print(x)

Output
WELCOME

h) string.lstrip([chars]) – Returns a copy of the string with leading characters removed.
Example
string1 = “Welcome”
x = string1.lstrip(‘Wel’)
print(x)

Output
come

i) string.rstrip([chars]) – Return a copy of the string with trailing characters removed.
Example
string1 = “Welcome”
x = string1.rstrip(‘come’)
print(x)

Output
wel

Lists in Python

A list is a common Python data type that may hold a series of values of any type. Square brackets are used to indicate the lists. lists are mutable.
Exmple
a. [] # list with no member, empty list
b. [1, 2, 3] # list of integers
c. [1, 2.5, 3.4, 2] # list of numbers(integers and floating point)
d. [‘a’, ‘b’, ‘c’] # list of characters
e. [‘a’, 1, ‘b’, 3.2, ‘New’] # list of mixed value types
f. [‘One’, ‘Two’, ‘Three’] # list of strings

Create lists

To create a list, put a number of expressions, separated by commas in square brackets.
Example
my_list = []
my_list = [33, 32, 54]

Create Empty list

The empty list is [ ]. you can also create an empty list as –
Example
my_list = list()

Create list from existing sequences

You can also use the built – in list type object to create lists from sequences as per the syntax given below –
Example
my_list = list(“Welcome”)
print(my_list)

Output
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

Creating list from keyboard input

You can use this method for creating lists of single characters or single digits via keyboard input.
Example
my_list = list(input(“Enter you name”))
print(my_list)

Output
Enter you name Welcome
Welcome
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

List vs String

Python defines a string as an organised collection of characters. A list is an ordered sequence of different object kinds, whereas a string is an ordered sequence of letters. This is important to keep in mind.

Difference between lists and string

a. Storage – Lists are stored in memory exactly like strings, except that because some of their objects are larger than others, they store a reference at each index insted of single character as in strings.

b. Mutability – Strings are not mutable, while lists are mutable. You cannot individual elements of a string in place, but lists allow you to do so. That is following statement is fully valid for lists.

List Operations

a. Traversing a list – Traversing a list means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a list, as per following syntax –
Example
my_list = [‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]
for a in my_list :
print(a)

Output
W
e
l
c
o
m
e

Joining lists

The concatenation operator + is used to joins two different lists and return the concatenated list.
Example
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
print(my_list1 + my_list2)

Output
[1, 2, 3, 4, 5, 6]

Repeating or Replicating lists

Like strings, you can use * operator to replicate a list specified number of times.
Example
my_list = [1, 2, 3]
print(my_list * 3)

Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Slicing the lists

List slicing, like string slices are the sub part of a list extracted out. you can use indexes of list elements to create list slices as per following format –
Example
my_list = [15, 33, 25, 14, 72, 52, 65, 47, 95]
print(my_list[3: -3])

Output
[14, 72, 52]

List manipulation

You can perform various operations on lists like, appending, updating, deleting etc.

Appending elements to a list

You can add items to an existing list. The append() method adds a single item to the end of the list.
Example
my_list = [10, 12, 14]
my_list.append(22)
print(my_list)

Output
[10, 12, 14, 22]

Updating Elements to a list

To update or change an element of the list in place, you just have to assign new value to the element’s index in list as per syntax –
Example
my_list = [10, 12, 14]
my_list[1] = 22
print(my_list)

Output
[10, 22, 14]

Deleting Elements from a list

You can also remove items from lists. The del statement can be used to remove an individual item, or to remove all items identified by a slice.
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
del my_list[2]
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

Making True copy of a list

Assignment with an assignment operator ( = ) on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory (called shallow copy).
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = list(my_list)
print(new_list)

Output
[10, 12, 14, 16, 18, 20, 22]

The index method

The function returns the index of first matched item from the list.

Example
my_list = [10, 12, 14, 16, 18, 20, 22]
print(my_list.index(14))

Output
2

The extend method

The extend() method is also used for adding multiple elements to a list. The extend() function works as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = [24, 26, 28, 30]
my_list.extend(new_list)
print(my_list)

Output
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]

The insert method

The insert() function inserts an item at a given position. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.insert(3, 44)
print(my_list)

Output
[10, 12, 14, 44, 16, 18, 20, 22]

The pop method

The pop() is used to remove the item from the list. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.pop(3)
print(my_list)

Output
[10, 12, 14, 18, 20, 22]

The remove method

The remove() method removes the first occurrence of given item from the list. It is used as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.remove(14)
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

The clear method

The method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.clear()
print(my_list)

Output
[]

The count method

This function returns the count of the item that you passed as argument. If the given item is not in the list, It will return zero.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
print(my_list.count(12))

Output
2

The reverse method

The reverse() reverses the items of the list. This is done “in place”, it does not create a new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.reverse()
print(my_list)

Output
[22, 12, 18, 16, 14, 12, 10]

The sort method

The sort() function sorts the items of the list, by default in increasing order. This is done “in place”, it does not create new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.sort()
print(my_list)

Output
[10, 12, 12, 14, 16, 18, 22]

Tuples in Python

The Tuples are depicted through parentheses, round brackets, following are some tuples in Python.
Example
a. () # tuple with no member, empty list
b. (1, ) # tuple with one member
c. (1, 2.5, 3.4, 2) # tuple of numbers(integers and floating point)
d. (‘a’, ‘b’, ‘c’) # tuple of characters
e. (‘a’, 1, ‘b’, 3.2, ‘New’) # tuple of mixed value types
f. (‘One’, ‘Two’, ‘Three’) # tuple of strings

Creating Tuples

To create a tuple, put a number of expressions, separated by commas in parentheses. That is, to create a tuple you can write in the form given below –
Example
my_tuple = tuple(“Welcome”)

Creating Empty Tuple

The empty tuple is (). you can also create an empty tuple as –
my_list = tuple()

Create Single Element Tuple

Making a tuple with a single element is tricky because if you just give a single element in round brackets.
Example
my_tuple = (1)

Creating Tuple from keyboard input

You can use this method of creating tuples of single characters or single digits via keyboard input.
Example
my_tuple = tuple(input(“Enter tuple elements “))
print(my_tuple)

Output
Enter tuple elements Welcome
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Difference between Tuples and Lists

Lists are mutable, while tuples are not. A tuple’s elements cannot be changed individually once they are in place, while lists let you do so.

Traversing a Tuple

Accessing and processing each element of a tuple is known as traversing it. It is simple to traverse or loop over the items in a tuple when using the for loop.
Example
my_tuple = (“Welcome”, “to”, “my”, “School”)
for a in my_tuple :
print(a)

Output
Welcome
to
my
School

Joining Tuples

The + operator used to join two different tuples.
Example
my_tuple1 = (1, 2, 3)
my_tuple2 = (4, 5, 6)
print(my_tuple1 + my_tuple2)

Output
(1, 2, 3, 4, 5, 6)

Repeating or Replicating Tuples

Like strings and lists, you can use * operator to replicate a tuple specified number of times.
Example
my_tuple = (1, 2, 3)
print(my_tuple * 3)

Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Slicing the tuples

Tuple slices, like list-slices or string slices are the sub part of the tuple extracted out. you can use indexes of tuple elements to create tuple slices as per following format –
Example
my_tuple = (1, 2, 3, 4, 5, 6)
new_tuple = my_tuple[ 2 : -2]
print(new_tuple)

Output
(3, 4)

Tuple Functions and Methods

1. The len() method – This method is used to find the length of the tuple.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(len(my_tuple))

Output
6

2. The max() method – This method is used to find the maximum value in the given tuples.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(max(my_tuple))

Output
6

3. The min() method – This method is used to find the minimum value in the given tuples.
my_tuple = (1, 2, 3, 4, 5, 6)
print(min(my_tuple))

Output
1

4. The index() method – It returns the index of an existing element of a tuple.
Example
my_tuple = (1, 2, 3, 4, 5, 6)
print(my_tuple.index(4))

Output
3

5. The count() function – The count() function returns the number of count memeber element in the given tuples.
Example
my_tuple = (1, 2, 3, 4, 5, 4)
print(my_tuple.count(4))

Output
2

6. The tuple() method – This method is actually constructor method that can be used to create tuples from different types of values.
Example
my_tuple = tuple(“Welcome”)
print(my_tuple)

Output
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Dictionaries in Python

A group of key-value pairs are assembled in dictionaries written in Python. Dictionary elements have the form of key:value pairs that link keys to values, making dictionaries mutable, unordered collections. To create a dictionary, you need to include the key:value pairs in curly braces as per following syntax –
Example
my_dict = {1:”One”, 2:”Two”, 3:”Three”}

Accessing Elements of a Dictionary

In dictionaries, the keys listed in the key are used to access the elements: value pairs according to the syntax displayed below –
Example
my_dict = {1: “One”, 2: “Two”, 3: “Three”}
print(my_dict[2])

Output
Two

Traversing a Dictionary

Accessing and handling each element in a collection is known as traversal. A dictionary’s elements can be easily traversed or repeated over with the help of the for loop.
Example
my_dict = { ‘Gujarat’: ‘Gandhinagar’, ‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}
keys = my_dict.keys()
print(keys)

Output
dict_keys([‘Gujarat’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

Adding Elements to Dictionary

We can add new elements to a dictionary using assignment operator. But remember the key being added must not exist in dictionary and must be unique.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict[‘Dept’] = ‘Sales’
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000, ‘Age’: 28, ‘Dept’: ‘Sales’}

Deleting Elements from a Dictionary

There are two different methods are used for deleting elements from a dictionary –
a) To delete the element from the dictionary you can use del command.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
del my_dict[‘Age’]
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

b) Another method to delete elements from a dictionary is pop() method.
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict.pop(‘Age’)
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

Dictionary Functions and Methods

a. The len() method – This method returns length of the dictionary, the count of elements in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(len(my_dict))

Output
3

b. The clear() method – The method removes all items from the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.clear())

Output
None

c. The get() method – Using get() method you can get the item with the given key.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.get(‘Name’))

Output
Amit

d. The items() method – This method returns all the items in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.items())

Output
dict_items([(‘Name’, ‘Amit’), (‘Salary’, 30000), (‘Age’, 28)])

e. The key() method – This method returns all of the keys in the dictionary as a sequence of keys.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.keys())

Output
dict_keys([‘Name’, ‘Salary’, ‘Age’])

f. The values() method – The method returns all the values from the dictionary as a sequence.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.values())

Output
dict_values([‘Amit’, 30000, 28])

g. The update() method – This method merges key:value pairs from the new dictionary into the original dictionary.
Example
emp1 = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
emp2 = {‘Name’ : ‘Rejesh’, ‘Salary’ : 35000, ‘Age’ : 29}
emp1.update(emp2)
print(emp1)

Output
{‘Name’: ‘Rejesh’, ‘Salary’: 35000, ‘Age’: 29}

Python Revision Tour 1 Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Python Revision Tour 1 Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Python Revision Tour 1 Class 12 Notes

Token in Python

The smallest unit in a Python programme is called a token. In python all the instructions and statements in a program are built with tokens. Different type of tokens in python are keywords, identifier, Literals/values, operators and punctuators –

Keywords

Words with a particular importance or meaning in a programming language are known as keywords. They are utilised for their unique qualities. There are 33 keywords in Python True, False, class, break, continue, and, as, try, while, for, or, not, if, elif, print, etc.

Identifiers

The names assigned to any variable, function, class, list, method, etc. for their identification are known as identifiers. Python has certain guidelines for naming identifiers and is a case-sensitive language. To name an identifier, follow these guidelines: –

  1. Code in python is case – sensitive
  2. Always identifier starts with capital letter(A – Z), small letter (a – z) or an underscore( _ ).
  3. Digits are not allowed to define in first character but you can use between.
  4. No whitespace or special characters are allowed.
  5. No keyword is allowed to define identifier.

Python Revision Tour 1 Class 12 Notes

Literals or Values

In Python, literals are the raw data that is assigned to variables or constants during programming. There are five different types of literals string literals, numeric literals, Boolean literals and special literals none.

a) String literals

The string literals in Python are represented by text enclosed in single, double, or triple quotations. Examples include “Computer Science,” ‘Computer Science’, ”’Computer Science”’ etc.
Note – Triple quotes string is used to write multiple line.
Example –
n1 = ‘Computer Science’
n2 = “Computer Science”
n3 = ”’Computer Science”’
print(n1)
print(n2)
print(n3)

b) Numeric Literals

Literals that have been use to storing numbers is known is Numeric Literals. There are basicaly three numerical literals –

  1. Integer Literal
  2. Float Literal
  3. Complex Literal

Example
num1 = 10
num2 = 15.5
num3 = -20
print(num1)
print(num2)
print(num3)

c) Boolean Literal

Boolean literals have only two values True of False.
Example
num = (4 == 4)
print(num)

d) Special literals none

The special literal “None” in Python used to signify no values, the absence of values, or nothingness.
Example
str = None
print(str)

Python Revision Tour 1 Class 12 Notes

Operators

In Python, operators are specialized symbols that perform arithmetic or logical operations. The operation in the variable are applied using operands.

The operators can be arithmetic operators(+, -, * /, %, **, //), bitwise operators (&, ^, |), shift operators (<<, >>), identity operators(is, is not), relational operators(>, <, >=, <=, ==, !=), logical operators (and, or), assignment operator ( = ), membership operators (in, not in), arithmetic-assignment operators (/=, +=, -=, %=, **=, //=).

Punctuators

The structures, statements, and expressions in Python are organized using these symbols known as punctuators. Several punctuators are in python [ ] { } ( ) @ -= += *= //= **== = , etc.

Barebones of a python program

a) Expressions – An expression is a set of operators and operands that together produce a unique value when interpreted.

b) Statements – Which are programming instructions or pieces of code that a Python interpreter can carry out.

c) Comments – Python comments start with the hash symbol # and continue to the end of the line. Comments can be single line comments and multi-line comments.

d) Functions – A function is a block of code that only executes when called. You can supply parameters—data—to a function. As a result, a function may return data.

e) Block or suit – In Python, a set of discrete statements that together form a single code block are referred to as suites. All statements inside a block or suite are indented at the same level.

Variables and Assignments

A symbolic name that serves as a reference or pointer to an object is called a variable in Python. You can use the variable name to refer to an object once it has been assigned to it. However, the object itself still holds the data.
Example
name = “Python”

Python Revision Tour 1 Class 12 Notes

Dynamic Type vs Static Type

The term “dynamic typing” refers to a variable’s type only being established during runtime. Whereas the statically type done at compile time in a python. Statically type of a variable cannot be change.

Multiple Assignments

Values are assigned by Python from right to left. You can assign numerous variables simultaneously in a single line of code using multiple assignment.
a) Assigning same value to multiple variables
n3 = n2 = n1 = 20
b) Assigning multiple values to multiple variables
n1, n2, n3 = 10, 20, 30

Simple input and output

Input 

Python automatically treats every input as a string input. To convert it to any other data type, we must explicitly convert the input. For this, we must utilize the int() and float() methods to convert the input to an int or a float, respectively.
example
name = input(‘What is your name’)
age = int(input(‘What is your age’)

Output

The print() method in Python allows users to display output on the screen. print statement automatically converts the items to strings.
example
num = 10
print(“Number is “)
print(num) # auto converted to string
print(34) # auto converted to string

Python Revision Tour 1 Class 12 Notes

Data Type

The classification or categorizing of data elements is known as data types. It represents the type of value that specifies the operations that can be carried out on a given set of data. In Python programming, everything is an object, hence variables and data types are both instances or objects.

Python has following data types by default.

Data types for Numbers

a) Integer – The integers represent by “int”. It contains positive or negative values.
b) Boolean – The boolean type store on True or False, behave like the value 0 and 1.
c) Floating – It is a real number with specified with decimal point.
d) Complex – Complex class is a representation of a complex number (real part) + (imaginary part)j. For example – 2+3j.

Data types for String

Strings in Python are collections of Unicode characters. A single, double, or triple quote are used to store string. There is no character data type in Python.
Example
name = ‘Computer Science’
name1 = “Computer Science’
name2 = ”’Computer Science”’

Lists

Lists are similar to arrays, it is a collections of data in an ordered way. list’s items don’t have to be of the same type in python.
Example
my_list = [1, 2, 3]
my_list1 = [“Computer”, “Science”, “Python”]
my_list2 = [“Computer Science”, 99]

Python Revision Tour 1 Class 12 Notes

Tuples

Tuple is similar to lists, It is also an ordered collection of python. The only difference between tuple and list is that tuples can’t be modified after it is created, So, that’s why it is known as immutable.
Example
my_tuple = (1, 2, 3)
my_tuple1 = (“Computer”, “Science”, “Python”)
my_tuple2 = (“Computer Science”, 99)

Dictionaries

In Python, a dictionary is an unordered collection of data values that can be used to store data values like a map. This dictionary can hold only single value as an element, Dictionary holds key:value pair.
Example
my_dict = (1: ‘Computer’, 2: ‘Mathematics’, 3: ‘Biology’)
my_dict = (‘Computer’: 1, ‘Mathematics’: 2, ‘Biology’: 3)

Mutable and Immutable Types

In Python, there are two different types of objects: mutable and immutable. It is possible to change mutable data types after they have been formed, whereas immutable objects cannot be altered once they have been created.

Mutable types

The mutable types are those whose values can be changed in place. Only three types are mutable in python lists, dictionaries and sets.

Immutable types

The immutable types are those that can never change their value in place. In Python, the following types are immutable in python integers, floating point numbers, Booleans, strings, tuples.

Python Revision Tour 1 Class 12 Notes

Expressions

In Python, an expression is made up of both operators and operands. example of expressions in python are num = num + 3 0, num = num + 40.
Operators in Python are specialised symbols that indicate that a particular type of computation should be carried out. Operands are the values that an operator manipulates. An expression is a collection of operators and operands, such as num = num + 3 0.

Type Casting (Explicit Type Conversion)

Type casting, often known as explicit type conversion, Users change the data type of an object to the required data type via explicit type conversion. To achieve explicit type conversion, we use predefined functions like int(), float(), str(), etc.

Math Library Functions

The Python standard library includes a built-in module called math that offers common mathematical functions.

  • math.ceil() – The ceil() function return the smallest integer.
  • math.sqrt() – The sqrt() function returns the square root of the value.
  • math.exp() – The exp() function returns the natural logarithm reised to the power.
  • math.fabs() – The fabs() function returns the absolute value.
  • math.floor() – The floor() function returns round a number down to the nearest intger.
  • math.log() – The log() function is used to calculate the natural logarithmic value.
  • math.pow() – The pow() function returns base raised to exp power.
  • math.sin() – The sin() function returns sine of a number.
  • math.cos() – The cos() function return the cosine of the value.
  • math.tan() – The tan() function return the tangent of the value.
  • math.degrees() – The degrees() converts angle of value from degrees to radians.

Python Revision Tour 1 Class 12 Notes

Statement Flow Control

Control flow refers to the sequence in which a program’s code is executed. Conditions, loops, and function calls all play a role in how a Python programme is controlled.
Python has three types of control structures –
a) Sequential – By default mode
b) Selection – Used in decision making like if, swithc etc.
c) Repetition – It is used in looping or repeating a code multiple times

Compound Statement

Compound statements include other statements (or sets of statements), and they modify or direct how those other statements are executed. Compound statements often take up numerous lines, however in some cases, a complete compound statement can fit on a single line.
Example
<compound statement header> :
<indented body containing multiple simple and/ or compound statement>

The IF & IF-ELSE conditionals

When using the if statement in Python, a Boolean expression is evaluated to determine whether it is true or false. If the condition is true, the statement inside the if block is executed. If the condition is false, the statement inside the else block is only executed if you have written the else block; otherwise, nothing happens.
Syntax of IF condition
if <conditional expression> :
     statement
     [statement]

Syntax of IF-ELSE condition
if <conditional expression> :
     statement
     [statement]
else :
     statement
     [statement]

Python Revision Tour 1 Class 12 Notes

Nested IF statement

One IF function contains one test, with TRUE or FALSE as the two possible results. You can test numerous criteria and expand the number of outcomes by using nested IF functions, which are one IF function inside of another.
Syntax of Nested IF statement
if condition :
     if condition :
          Statement
     else :
          Statement

Looping Statement

In Python, looping statements are used to run a block of statements or code continuously for as many times as the user specifies. Python offers us two different forms of loops for loop and while loop.

The For loop

Python’s for loop is made to go over each element of any sequence, such a list or a string, one by one.
Syntax of FOR loop –
for <variable> in <sequence> :
     statements_to_repeat

The range() based for loop

The range() function allows us to cycle across a set of code a predetermined number of times. The range() function returns a series of numbers and, by default, starts at 0 and increments by 1 before stopping at a predetermined value.
Syntax –
range(stop)
range(start, stop)
range(start, stop, step)

Python Revision Tour 1 Class 12 Notes

The While loop

A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remain true.
Syntax –
while <logical expression> :
loop-body

JUMP Statemement – break and condinue

Python offers two jump statement – break and continue – to be used within loops to jump out of loop-iterations.

The break Statement

A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.
Syntax –
break

Example –
a = b = c = 0
for i in range(1, 11) :
     a = int(input(“Enter number 1 :”))
     b = int(input(“Enter number 2 :))
     if b == 0 :
          print(“Division by zero error! Aborting”)
          break
     else
          c=a/b
          print(“Quotient = “, c)
print(“program over!”)

The continue statement

Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
Syntax –
continue

Python Revision Tour 1 Class 12 Notes

Loop else statement

Python supports combining the else keyword with both the for and while loops. After the body of the loop, the else block is displayed. After each iteration, the statements in the else block will be carried out. Only when the else block has been run does the programme break from the loop.
Syntax –
for <variable> in <sequence> :
     statement1
     statement2
else :
     statement(s)

while <test condition> :
     statement1
     statement2
else :
     statement(s)

Nested Loops

A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop.
The following is an example of a nested loop :
for i in range(1,6) :
     for j in range(1, i) :
          print(“*”, end =’ ‘)
     print()

error: Content is protected !!