Python Notes 11th Cs Merged
Python Notes 11th Cs Merged
Following
are key features of Python :
Python has a clean and easy-to-read syntax, making it accessible for beginners.
Its readability helps developers understand and write code quickly.
2. Interpreted Language
3. Dynamically Typed
In Python, you do not need to declare the data type of a variable when you create it.
The interpreter automatically determines the data type at runtime, which simplifies coding.
4. High-Level Language
It allows you to focus on coding logic rather than managing memory and other low-level
operations.
5. Cross-Platform Compatibility
Python programs can run on various operating systems like Windows, macOS, and Linux
without requiring any changes to the code.
Python is free to download and use, and its source code is open for modification and
distribution.
8. Versatile
Python is used in various fields such as web development, data science, artificial intelligence,
machine learning, automation, and more.
Its versatility makes it a popular choice across different domains.
9. Case sensitive
Python is a case sensitive language meaning name a and A both are different.
INSTALL PYTHON:
Steps to install:
Type python --version and press Enter. You should see the version of Python you installed.
Interactive Mode is a way of using the Python interpreter in a command-line interface (CLI) where you
can type Python code and get immediate feedback. This mode is particularly useful for testing small
code snippets, learning, and experimenting with the language.
How to Use Interactive Mode:
Script Mode is when you write your Python code in a file, which is then executed by the Python
interpreter as a whole. This mode is useful for writing larger programs that consist of multiple lines of
code.
1. Tokens:
o Tokens are the smallest pieces of a Python program.
o They include keywords, identifiers, literals, operators, delimiters, and comments.
2. Keywords:
o Keywords are reserved words that have special meaning in Python.
o You cannot use keywords as names for variables, functions, or classes.
o Examples of keywords: if, else, while, for, def, class, import, from.
3. Identifiers:
o Identifiers are names used to identify variables, functions, classes, modules, or other
objects.
o They must start with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits
(0-9), or underscores.
o Identifiers are case-sensitive (e.g., myVariable and myvariable are different).
o Examples: age, my_function, _temp, ClassName.
4. Literals:
o Literals are constant values that appear directly in the code.
o Types of literals:
String Literals: Text enclosed in single (') or double (") quotes. Example:
'hello', "world".
Integer Literals: Whole numbers. Example: 123, 0, -45.
Float Literals: Numbers with a decimal point. Example: 3.14, 0.001, -2.0.
Boolean Literals: True or False.
None: Represents the absence of a value.
5. Operators:
o Operators are symbols that perform operations on variables and values.
o Types of operators:
Arithmetic Operators: + (addition), - (subtraction), * (multiplication), /
(division), % (modulus), ** (exponent), // (floor division).
Comparison Operators: == (equal), != (not equal), > (greater than), < (less
than), >= (greater than or equal to), <= (less than or equal to).
Assignment Operators: = (assign), += (add and assign), -= (subtract and
assign), *= (multiply and assign), /= (divide and assign), etc.
Logical Operators: and, or, not.
Bitwise Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right
shift).
6. Delimiters:
o Delimiters are symbols that separate code into manageable parts or indicate the start
and end of code blocks.
o Examples:
Parentheses: () used in function calls or to group expressions.
Brackets: [] used for lists, arrays, or indexing.
Braces: {} used to define dictionaries or sets.
Comma: , used to separate items in a list or function arguments.
Colon: : used after conditions in control flow statements or to define
dictionaries.
Semicolon: ; used to separate statements on the same line.
Quotes: ', " used to denote string literals.
Backslash: \ used to continue a statement on the next line.
7. Comments:
o Comments are notes in the code for the programmer. Python ignores them when
running the program.
o Single-line comments start with #. Example: # This is a comment.
o Multi-line comments can be written inside triple quotes (''' or """). Example:
python
Copy code
"""
This is a
multi-line comment.
"""
8. Whitespace:
o Whitespace includes spaces, tabs, and new lines.
o Whitespace separates tokens and helps structure the code.
o Indentation (spaces or tabs at the beginning of a line) is used to define the scope of
loops, functions, classes, and conditionals.
o Example:
python
if condition:
#code
else condition:
#code
These tokens together form the syntax and structure of Python programs, allowing us to write and
execute code.
What is a Variable?
Characteristics of Variables
Example:
age = 16
name = "Alice"
height = 5.6
4. Cannot use reserved keywords: Keywords like for, if, while, etc., cannot be used as variable
names.
Valid name examples:
my_variable = 10
_myVariable = "Hello"
myVariable123 = 3.14
You can change the value of a variable at any time by assigning a new value to it.
Multiple Assignment
EX 2.)
If the value is same for all the variables, you can assign it using = sign. E.g.
Another Example:
Print a Literal value :
Examples:
To print value of a variable , just write the name of variable in the print() function
without any quotes.
e.g. x= 5
print(x)
To print value of multiple variables : write the name of variables separated by
comma in print() function.
x=10
y=”hello”
print(x,y)
If you want to use strings and variables together in print() function,
Write the string in quotes
Use comma between them
Write variable names without quotes.
input() Function in Python
The input() function in Python is used to take input from the user during the execution of
a program. It's a crucial part of interactive programs where the behavior of the code
depends on user-provided data.
The input() function allows a program to pause its execution and wait for the user
to type some data and press the Enter key.
The data entered by the user is always a string by the input() function, which can
then be stored in a variable or used directly.
2. Basic Syntax
variablename: The variable in which user want to store the input value.
Examples:
Value entered using input() function is always a string. No mathematical operations can
be performed on it.
This can be done using int(), float() functions as shown in the example given below:
Datatype:
Variables can store data of different types, and different types can do different things.
Each value in a programming language has a type, which defines what operations can
be performed on that data.
You can get the data type of any variable by using a built-in function
called type() function:
Sequence types help represent sequential data stored into a single variable. There are
three types of sequences used in Python:
String
List
Tuple
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
You can also assign a multiline string to a variable by using three quotes.
To know the type we can use type() function as shown in example below:
Strings are sequences of characters, and each character in a string has a specific
position or index. You can use this index to access individual character.
b.) List
A list in Python is a collection that can hold multiple items, which can be of different
types (like integers, strings, or even other lists). Lists are one of the most versatile and
commonly used data types in Python.
Lists are created by placing all the items (elements) inside square brackets [],
separated by commas
Examples:
You can print the complete list by using listname in print() function.
You can also access the individual items using their index. Index starts at 0.
listname[index]
c.) Tuple
A tuple a collection that can hold multiple items. It is also used to store multiple values in
a single variable.
Examples:
Note: If there’s only one item in a tuple it must have a comma after it.
tuple1 = 10,
You can print the complete tuple by using tuple name in print() function.
4. NoneType
In Python None is a special constant that represents the absence of a value or a null/empty
value. Its type is NoneType.
5. Set
6. Dictionary:
{ key1: value1 ,
key2 : value2 }
Creating a dictionary :
Print a dictionary:
print(dictionaryname)
Type: use type() function
Types of Errors in Programming:
These errors can prevent your program from running correctly or at all.
1. Syntax Errors
A Syntax Error occurs when the code you write does not follow the rules of the
programming language. It’s like making a grammatical mistake in a sentence.
Example 1:
print("Hello World”
Example 2:
L1 = [ 10,20 30]
2. Logical Errors
A Logical Error occurs when the code is running, but it doesn't do what you wanted it to
do. The logic of the program is flawed, leading to incorrect results.
a = 10
b = 20
sum = a - b
print("Sum:", sum)
sum = a + b
print("Sum:", sum)
3. Run-Time Errors
These errors happen due to illegal operations like dividing by zero, trying to access an
index that doesn’t exist in a list, or using variables that haven't been initialized.
Example 1:
L1 = [1, 2, 3]
print(L1[5])
Example 2:
X=10
print(X/0)
1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. Assignment operators
5. Identity operators
6. Membership operators
// gives quotient as output when x is divided by y e.g. here x//y gives output 3.
% gives remainder as output when x is divided by y e.g. here x%y gives output
Write a program that takes two numbers as input from user and uses all arithmetic
operators on them and print the result.
2. Comparison Operators or Relational Operators.:
These operators are used to compare two values.
Example:
3. Assignment operators : These are used to assign value to the variables.
Example:
x,y = 30, 20
x,y = 5, 10 x -= y
x += 5 print(x)
y = y+5
print(x) y+=x
print(y) print(y)
Output: Output:
10 10
15 30
Example using all the assignment operators
4. Logical Operators
and: Returns True if all operands are True.
or: Returns True if at least one operand is True.
not: Returns the negation of the operand (converts True to False and vice versa)
.
Logical operators with comparison operators:
5. Identity Operators:
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Examples:
6. Python Membership Operators
1. in
2. not in
1. 'in' Operator
It returns True if the specified value does not exist in the sequence.
If the value exists, it returns False.
Example 1 : write a program to check if a substring is a part of a string
Identity operators are used to compare the memory locations of two objects to see if
they refer to the same object.
Even if two variables have the same value, they may not be the same object.
There are two identity operators:
1. is
2. is not
1. 'is' Operator
Note:
For Immutable Data Types in Python: Numbers (int, float, complex),Strings (str), Tuples
(tuple),Booleans (bool) = = operator and is operator works the same.
For mutable data types list and dictionary = = and is operator works different.
2. 'is not' Operator
Associativity:
Associativity determines the order of evaluation when two operators of the same
precedence appear in an expression. Operators can have left-to-right or right-to-left
associativity.
All operators in the above given table except **, logical not have left to right
associativity.
** and logical not has right to left associativity
Example: left to right
print(10 / 5 * 2)
/ and * have the same precedence.
Since they follow left-to-right associativity:
Output: 4.0
3 ** 2 → 9
2 ** 9 → 512
Output: 512
CBSE 12th Board questions:
1. not ((True and False) or True)
Ans: False
2. print(True or not True and False)
ANs : true
3. What will be the output of the following expression?
24//6%3 , 24//4//2 , 48//3//4
Ans: 1,3,4
4. print(25 // 4 + 3**1**2 * 2)
Ans : 12
5. print(2**3 + (5 + 6)**(1 + 1))
ANs : 129
6. print(16-(3+2)*5+2**3*4)
Ans: 23
7. 8 and 13 > 10
Ans : True
8. 7%5==2 and 4%2>0 or 15//2==7.5
Ans: False
Conditional Statements in Python:
In Python, we use conditional statements to make decisions in our code. These are
executed based on whether a condition is True or False.
1. if Statement
Syntax:
Example:
The elif statement checks another condition if the first if condition is False.
You can have multiple elif conditions.
SYNTAX:
OUTPUT:
3. else Statement
The else statement runs when all previous conditions are False.
It s optional
No condition is needed with else statement.
Syntax:
EXAMPLE 3: Write a program that checks if a given number is divisible by both 3&5 or
by 3 or by 5 or by none of them.
EXAMPLE 4: Write a program that to take a name from the user. If the name starts with
a or p , it displays "Name accepted"; otherwise, it displays "Name not accepted".
Example 5 Write program that takes a user ID and password as input and checks if
they are "root" and "admin" respectively. If both match, it displays "Login successful";
otherwise, it displays "Incorrect username/password".
QUES 1 Write a Python program to display the day of the week based on a
number entered by the user, using if-elif-else statements
QUES 3 Write a program to check if the sum of all elements of the list() is even or odd.
QUES 4 Write a program that takes two numbers from user. Ask which operation user wants to perform.
1. Addition
2. Subtraction
3. Multiplication
4. division
Implements the respective operation on two numbers and displays the output.
Ques 5. Write a program to ask a user to enter a character and check if it is a vowel or a consonant.
Ques 6. Write a program to ask the user to enter a student name. There is a list that already contains
some students. If this list contains the entered name , display student already exists otherwise display
student added to the list.
Loop:
1. for loop
2. while loop
for loop:
for loop is used to repeat a block of code for a given no of times.
It repeats the code for each item in a sequence, e.g. range given by range() function or a list,
tuple, or string.
It lets you go through each item one by one and perform actions with/on it.
variable: A user defined name that takes each value from the sequence one at a time.
sequence: A collection of items (like a list, tuple, string, or range) that you want to iterate over.
The code block below the for loop is the code that runs in each round.
Example:
In this example:
Ques 5 Write a program to print all numbers divisible by some number x in first n natural numbers.
range() function:
It’s most often used in for loops to repeat actions a certain number of times.
Syntax:
start (optional): The first number in the sequence. If not specified, it starts from 0.
stop (required): The number at which the sequence stops (but doesn’t include it).
step (optional): The amount by which the sequence increments. If not specified, it
defaults to 1.
Example
range(n) : 0 to n-1
range(m,n) : m to n-1
Ques Write a program that prints a sequence where start and stop
are entered by user.
Ques Write a program that prints a sequence where start and stop
and step are entered by user .
Example of negative step:
for loop with a string:
Syntax:
Q4 Program to calculate and print sum of only even values in a given list.
Syntax:
variable: A temporary name for the current element in the list or tuple.
list_name: The list to iterate through.
Q4 Program to calculate and print sum of only even values in a given list.
Solve:
1. Write a program to display the numbers from a list which are greater than 60 and
less than equal to 80.
L1= [110,30,45,78,98,76,80,67]
2. Write a program to calculate the total numbers in a list which are greater than 60
and less than equal to 80.
Also calculate their sum and print both.
L1= [110,30,45,78,98,76,80,67]
What is a while Loop?
A while loop in Python is used to repeatedly execute a block of code as long as a specified
condition is True. A loop has following parts:
1. Initialization
Variables used in the loop are initialized before the while loop starts.
This gives the loop a starting point.
2. Condition
3. Body
The block of code inside the loop that executes repeatedly as long as the condition is True.
It must be indented to indicate it is part of the loop.
4. Update Statement
A part of the loop body that increases/decreases the variables involved in the condition.
It Ensures the condition will eventually become False to avoid an infinite loop.
Example 3: program to print numbers divisible by both 3 and 5 in first n numbers using while
loop in reverse order
Example 4: program to print sum of odd numbers in first n numbers using while loop
Example 5 program to count numbers divisible by 3 in first n numbers using while
The else block runs when the for loop completes all its iterations normally (without a break).
If a break statement is encountered, the else block is skipped.
When break statement runs, else block doesn’t run.
In the following example, when i is 2 , ‘if’ condition becomes true and the break statement
runs. Loop is terminated. So else block will not run.
In the following example, ‘if’ condition never becomes true and the break statement never
runs. So else block will run.
2. else with while
In first example, break statement stops the loop so else block will not run.
In this example, break statement never runs. loop runs completely. so else block will run.
String:
A datatype
Used to store text value
Immutable data type.
Strings are ordered.
Strings are indexed, the first character has index [0], the second has index [1] etc.
Creating a String : Strings in python are surrounded by either single quotation marks, or
double quotation marks.
String Length :
Length of a string means no of characters in the string, use the len() function.
Syntax: len(string)
Indexing:
Strings are indexed.
you can access each character by using the index number.
First character has index zero.
Index 1 refers to 2nd character, index 2 refers to 3rd character and so on.
Negative Indexing
Negative index means to start from the end.
-1 refers to the last character, -2 refers to the second last character etc.
E.g.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Note:
When no end index is provided, the range will go on to the end of the string
When no start index is provided, the range will be from the start of string
str[2:5] It will start at index 2 (included) and end at index 5 (not included).
str[:5] Will start from the 0 index and end at index 5(not included)
str[-5:-2] -5 means 5th character from the last. Range will start from 5th character
from the end to the 2nd character from the end( not included)
str[:-5] Range will start from 0 index to the 5th character from the end(not
included).
str[-3:] Range will start from 3rd last character to the end of the string.
Slicing a string using three values in [] : [ start: end: step]
step refers to how many characters to skip after the first character from the string.
str[2:14: 2] It will give every 2nd character starting at index 2 (included) and ending at index 14 (not included).
str[2:14:3] It will give every 3rd character starting at index 2 (included) and ending at index 9 (not included).
str[-8:-1:2] It will give every 2nd character starting at index -8 (included) and ending at index -1(not included).
str[14:2: -2] start at index 14 (included) and end at index 2 (not included). Keep adding -2 to start index.
14,12,10,8,6,4
str[12:1:-3] start at index 12 (included) and end at index 1 (not included). Keep adding -3 to start index. 12,9,6,3
str[-3:-14:-2] start at index -3 (included) and end at index -14 (not included). Keep adding -2 to start index.
-3,-5,-7,-9,-11,-13
Looping a String:
We need to use a loop if we want to Get or print each character one by one.
But changing any character in a string is not allowed as string is an immutable data type.
This operation is not allowed and will give an error.
String Operations:
1. String Concatenation
To concatenate, or combine, two strings you can use the + operator.
2. * operator with string
Note:
str = “hello”
print(str+2) --->This will give an error.
print(str + “2”) -----> hello2
str = “hello”
print(str * “3”) -----> This will give an error.
print(str * 3) -----> hellohellohello
4. islower() Returns True if all characters in the string are lower case otherwise
returns False.
5. isalpha() Returns True if all characters in the string are alphabets (a-z A-z) only
otherwise returns False
6. isdigit() Returns True if all characters in the string are digits(0-9) only otherwise
returns False
7. isalnum() Returns True if all characters in the string are alphabets(a-z A-z) or
digits (0-9)otherwise returns False
10. endswith() Returns true if the string ends with the specified value otherwise False
11. startswith() Returns true if the string starts with the specified value otherwise False
12. count() count and Return the number of times a given character(s) appears in
a string
14. find() Searches the string for a specified character(s) and returns the position
of first occurrence where it was found.
If given character(s) is not found it returns -1
15. index() it is similar to find().
Searches the string for a specified character(s) and returns the position
of first occurrence where it was found.
But if a given character(s) is not found it raises an exception or error.
16.1 strip() strip() removes the spaces from the start and end of a string.
16.2 rstrip() rstrip() removes the spaces from the end of a string.
16.3 lstrip() lstrip() removes the spaces from the start of a string.
17 split()
The split() method splits a string into a list.
Print a list:
To print a list use syntax: print(listname)
List Length :
Syntax: len(listname)
Negative Indexing
Negative index means to start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
You can specify a range of indexes by giving a start and end index.
the return value will be a new list with the specified items.
Note:
list1[2:5] It will start at index 2 (included) and end at index 5 (not included).
list1[:5] Will start from the 0 index and end at index 5(not included)
list1[-5:-2] -5 means 5th item from the last. Range will start from 5th item from the end to the
2nd item from the end( not included)
list1[:-5] Range will start from 0 index to the 5th item from the end.-5 not included
list[-3:] Range will start from 3rd item from the end to the end of the list.
Slicing a list using three values in [] : [ start: end: step]
step refers to how many items to skip after the first item from the list.
It will give every 2nd item starting at index 2 (included) and ending at index 9 (not included).
list1[2:9: 2] keep adding 2 to start index. 2,4,6,8
list1[2:9:3] It will give every 3rd item starting at index 2 (included) and ending at index 9 (not included).
list1[-8:-1:2] It will give every 2nd item starting at index -8 (included) and ending at index -1(not included).
list1[9:2: -2] start at index 9 (included) and end at index 2 (not included). Keep adding -2 to start index. 9,7,5,3
list1[10:1:-3] start at index 10 (included) and end at index 1 (not included). Keep adding -3 to start index. 10,7,4
list1[-3:-9:-2] start at index -3 (included) and end at index -9 (not included). Keep adding -2 to start index.
-3,-5,-7
Adding an item to a list:
append() will always add item to the end of a insert() method will insert an item at a specified
list. index.
Example: in list1 you want to add ‘peach’ Example: in list1 you want to add ‘peach’ at
at the end. index 2.
list1.append(‘peach)
list1.insert(2,’peach’)
The remove() method removes the specified The pop() method removes the specified index.
item.
Example 1: remove item with index 2 from list2
Example 1: remove cherry from the list2
list2.remove(‘cherry’) list2.pop(2)
Dictionary methods:
1. keys() : It returns a list containing all the keys of dictionary.
syntax
dictionary.keys()
List2 = [10,20,10,40,30,10,50]
5. sort() This function sorts the original list in alphabetical or numerical order .
6. index() The index() method returns the index of the first occurrence of the
given value.
There are several ways to join, or concatenate, two or more lists in Python.
To delete a list : Use del keyword to delete a list completely from memory.
del listname
e.g.
del list1
print(list1) # now This line will give error as list1 has been already deleted.``
Dictionary:
It is a collection key and value pairs.
It is mutable data type.
It is unordered or non-sequential data type.
Key must be unique and immutable.
It is created using {} curly brackets.
Keys and values are separated by colon. i.e. key : value
Each key value pair is separated by comma. i.e. { key1: value1 , key2 : value2 }
Creating a dictionary :
Example: Create a student dictionary with name s and keys name, class and marks.
s={
'name' : 'Sachin',
'class': 12,
'marks': 75
}
Print a dictionary:
To print a dictionary use following syntax:
print(dictionary_name)
Dictionary Length :
To determine how many items a
dictionary has, use the len() function.
Syntax: len(dictionary_name)
Looping through a dictionary: you can use for loop for this
1. To get values of a dictionary one by one, 2. To get keys of a dictionary one by one,
You can use either of the two ways given You can use either of the two ways given below.
below.
Dictionary methods:
1. keys() : It returns a list of all the keys in a dictionary.
syntax
dictionary_name.keys()
2. values() : It returns a list of all the values in a dictionary.
4. clear()
It deletes all the data from the dictionary.
5. fromkeys() : It creates and returns a new dictionary with the given keys.
All the keys will have same value if provided. If no value is provided, None is used as default.
del keyword:
Deleting a dictionary: In the given example, when we try to print dictionary s1 , it gives error. Because del
keyword has already deleted s1. So it doesn’t exist anymore. Similarly it can be used with any list or tuple.
PREV YEAR QUES:
Tuple:
Used to store multiple values in a single variable.
Tuple is immutable data type.
Tuple is ordered.
Values in a Tuple can be of any other data type.
Duplicates are allowed.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Empty tuple
T1 = ()
Important :
Tuple with one value : you need to add comma after first value
T1=(2, )
Print a Tuple:
To print a Tuple use syntax: print(Tuplename)
e.g. print(Tuple1)
Tuple Length :
Syntax: len(tuple1)
Access Tuple Items:
Tuple items are indexed.
you can access them by using the index number with the Tuple name.
First item has index zero.
Index 1 refers to 2nd item, index 2 refers to 3rd item and so on.
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
Tuple slicing :Exactly Similar to List slicing (refer to List slicing in the notes)
[start:stop]
or
[start : stop : step]
Looping a Tuple: (similar to a list)
We need to use a loop if we want to Get or print item one by one.
T1=(10,20,30)
T1[1] = 40 #not allowed
4. sorted() This function returns a list of sorted Tuple items in alphabetical or numerical order.
By default the order is ascending.
6. sum ()
This functions returns the sum of all tuple items.
Tuples with + operator:
Tuple with * operator: Tuple Multiplied by n means Tuple elements are repeated n number of
times.
To delete a Tuple : Use del keyword to delete a Tuple completely from memory.
del Tuplename
e.g.
del Tuple1
print(Tuple1) # now This line will give error as Tuple1 has been already deleted.``
module : A module is simply a Python file (.py) that contains functions and variables.
Built-in Modules: These modules come pre-installed with Python.
Examples: math, random, statistics etc.
To use a module name in your code, you need to import it.
Syntax: import modulename
1. math module:
The math module in Python provides various mathematical functions and constants.
2. random module
random module in Python is used to generate random numbers and perform random selections.
3. statistics module:
This module in Python provides functions to perform statistical calculations like mean, median, mode
etc.