0% found this document useful (0 votes)
16 views103 pages

Python Notes 11th Cs Merged

Uploaded by

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

Python Notes 11th Cs Merged

Uploaded by

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

Python is a popular high-level programming language known for its simplicity and readability.

Following
are key features of Python :

1. Simple and Easy to Learn

 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

 Python is an interpreted language, meaning that code is executed line by line.


 This makes debugging easier since errors are identified as soon as they occur.

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.

6. Procedural and Object-Oriented

 Python supports procedural programming through the use of functions.


 Python supports object-oriented programming (OOP) which allows you to create classes and
objects.

7. Free and Open Source

 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:

1. Open a Web Browser:


2. Go to the official Python website: python.org.
3. download the latest version of Python for Windows.
4. Run the installer( double click the .exe file)

Type python --version and press Enter. You should see the version of Python you installed.

RUN PYTHON CODE:

Interactive Mode in Python

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:

1. Open Command Prompt:


2. Start the Python Interpreter:
o Type python or python3 (depending on your Python installation) and press Enter.
3. Enter Commands:
o You can now type Python commands and see the output immediately.

Script Mode in Python

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.

How to Use Script Mode:

1. Write Code in a Text Editor:


o Open your preferred text editor (e.g., Notepad, Sublime Text, VS Code).
o Write your Python code and save the file with a .py extension (e.g., demo.py).
2. Execute the Script:
o Open Command Prompt.
o Navigate to the directory where your script is saved.
o Run the script by typing python demo.py or python3 demo.py and pressing Enter.
A PYTHON PROGRAM IS MADE UP OF FOLLOWING COMPONENTS:

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?

 A variable is a container for storing data values.


 A Python variable is a name given to a memory location.
 In Python, a variable is created when you assign a value to it using the equals sign ( =).
 Variables in Python are dynamic, meaning they can store data of any type,
 Type of data a variable can change during program execution.

Characteristics of Variables

1. Name: The identifier given to a variable.


2. Value: The data stored in the variable.
3. Type: The type of data the variable holds (e.g., integer, float, string,boolean etc.).

Declaring and Initializing Variables

 In Python, you don't need to declare the type of avariable.


 A variable is created the moment you first assign a value to it.

Example:

age = 16

name = "Alice"

height = 5.6

Variable Naming Rules

1. Must begin with a letter (a-z, A-Z) or an underscore (_).

2. Can include letters, numbers (0-9), and underscores (_).

3. Case-sensitive: age and Age are different variables.

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

Invalid name Examples:

123variable = 5 # Starts with a number

my-variable = "test" # Contains a hyphen

for = 7 # Uses a reserved keyword

Changing the Value of a Variable

 You can change the value of a variable at any time by assigning a new value to it.

Multiple Assignment

 Python allows you to assign values to multiple variables in a single line.


 No of values on the left hand side must be equal to right hand side otherwise error will occur.
Examples: 1.)

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 :

 The value can be of any type (int,float,string etc.)


 To print a literal value, just write the value in print() function.
 Number (integer,float) is written without any quotes.
 String value is written in single(‘’) or double quotes(“”)

Examples:

Print value of a variable:

 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.

1. What is the input() Function?

 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 = input("Prompt message")

variablename: The variable in which user want to store the input value.

"Prompt message": (Optional) A message that is displayed to the user, indicating


what kind of input is expected.

Examples:
Value entered using input() function is always a string. No mathematical operations can
be performed on it.

So to do that we have to convert it in integer, float etc.

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.

Getting the Data Type

You can get the data type of any variable by using a built-in function
called type() function:

e.g. To know the datatype of x


x=5
print(type(x))
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a decimal number, or even a complex number.
 Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.
 Float – This value is represented by the float class. It is a real number. It is
specified by a decimal point.
 Complex Numbers – A complex number is represented by a complex class. It is
specified as
(real part) + (imaginary part)j
For example : 2+3j

Note : All numeric data types are immutable datatypes.

2. Boolean Data Type in Python


Python Data type can have only one of the two built-in values, True or False.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will
throw an error
3. Sequence Type

Sequence types help represent sequential data stored into a single variable. There are
three types of sequences used in Python:

 String
 List
 Tuple

a.) Strings (Immutable data type)

Strings in python are surrounded by either single quotation marks, or double quotation
marks.

e.g. 'hello' is the same as "hello".

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.

Key Points About String Indexing:

 The first character in a string has an index of 0.


 The second character has an index of 1, and so on.

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.

Key Features of Lists:

1. Ordered: Items in a list have a defined order


2. Indexable: You can access individual items in a list by their index (position in the
list), starting from 0 for the first item.
3. Heterogeneous: A list can contain items of different types. For example, a list
can have integers, strings, Boolean etc.
4. Changeable : new items can be added to a list. Items can be deleted. Items can
be changed.
5. List is mutable datatype.
How to Create a List:

 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.

 type() function is used to know the type.

You can also access the individual items using their index. Index starts at 0.

Index of first element is 0, 2nd element is 1, 3rd element is 2 and so on.

To access an item in list use following syntax:

 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.

Key Features of Lists:

6. Ordered: Items in a tuple have a defined order


7. Indexable: You can access individual items in a tuple by their index (position in
the tuple), starting from 0 for the first item.
8. Heterogeneous: A tuple can contain items of different types. For example, a
tuple can have integers, strings, Boolean etc.
9. Un-Changeable :Unlike list , once created tuple items cannot be
changed/deleted or added.
10. Tuple is immutable datatype.

How to Create a Tuple:

 A Tuple is created by placing all the items (elements) inside parentheses () or


without parentheses, separated by commas.

Examples:
Note: If there’s only one item in a tuple it must have a comma after it.

e.g tuple1 = (10,)

tuple1 = 10,

 You can print the complete tuple by using tuple name in print() function.

 type() function is used to know the type.

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

 Sets are used to store multiple items in a single variable.

 A set is a collection which is unordered, unchangeable and unindexed.


 Set can’t have duplicate values.
 Set is also heterogeneous datatype meaning it can contain elements of
different data types.

A set is created using curly brackets with comma separated values.

To print a set, use set name in print() function.

type() function is used to know the type.

6. Dictionary:

 It is a collection of 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 changeable. Items can be added/deleted/changed.
 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 dictionary with keys name, class and marks.

Print a dictionary:

To print a dictionary use following syntax:

print(dictionaryname)
Type: use type() function
Types of Errors in Programming:

When writing a program, you might face different types of errors.

These errors can prevent your program from running correctly or at all.

Understanding these errors helps in debugging and improving your code.

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”

Errors: Missing the closing bracket.

Example 2:

L1 = [ 10,20 30]

Errors: Missing comma after 20

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.

Example: code for printing sum of two numbers

a = 10
b = 20
sum = a - b
print("Sum:", sum)

Error: The code subtracts b from a instead of adding them.

Correct the logic by using the addition operator:

sum = a + b
print("Sum:", sum)

3. Run-Time Errors

A Run-Time Error occurs when the program is running.

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])

Error: IndexError: list index out of range

Trying to access index 5 in list L1 that doesn’t exist.

Example 2:

X=10

print(X/0)

Error: ZeroDivisionError: division by zero


What is an Operator?

In programming, an operator is a symbol that tells the computer to perform a specific


operation or calculation. Operators are used to manipulate data and variables to produce
a result. These data and variables are called operands.

Types of operators in python:

1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. Assignment operators
5. Identity operators
6. Membership operators

1.Arithmetic Operators in Python

Arithmetic operators are used to perform common mathematical operations like


addition, subtraction, multiplication, etc. Here’s a list of the arithmetic operators available
in Python:

Note (/,//,%) : x= 10, y= 3


/ gives absolute result with decimal when x is divided by y e.g.here x/y gives output 3.33333

// 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

Membership operators are used to check whether a value is present in a sequence,


such as a string, list, tuple, or set. There are two membership operators:

1. in
2. not in

1. 'in' Operator

 It returns True if the specified value exists in the sequence.


 If the value is not found, it returns False.

2. 'not 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

Example 2 : write a program to check if an item is a part of a list/tuple

# entered item 10 is a string. List contains integer 10.

#in operator is case sensitive.

6. Identity Operators in Python

Identity operators are used to compare the memory locations of two objects to see if
they refer to the same object.

Identity operators compare memory locations, not values.

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

 Returns True if both variables point to the same object in memory.


 If they do not refer to the same object, it returns False.

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

 Returns True if both variables refer to different objects in memory.


 If they refer to the same object, it returns False.
 It reverses the result of is operator.
OPERATOR PRECEDENCE:
In Python, operator precedence determines the order in which operators are evaluated
in an expression. Operators with higher precedence are evaluated before operators
with lower precedence.

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:

 10 / 5 → 2.0 #10/5 will be evaluated first


 2.0 * 2 → 4.0

Output: 4.0

Example: right to left


print(2 ** 3 ** 2)
** follows right-to-left associativity.
So, it is evaluated as:

 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

 The if statement checks a condition.


 If the condition is True, the block of code inside it runs.
 if statement can be used alone with or without elif or else.

Syntax:

Example:

2. elif Statement (Else If)

 The elif statement checks another condition if the first if condition is False.
 You can have multiple elif conditions.

SYNTAX:

Example: Write a program to display grades based on marks entered by user.


OUTPUT:

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: Write a program to find a given number is odd or even.


EXAMPLE 2: Write a program that takes two numbers from the user and check if
number 1 is divisible by number 2 or not.

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 2 Write a program to display no of days based on month name.


UNSOLVED

QUES 3 Write a program to check if the sum of all elements of the list() is even or odd.

e.g for L1 =[ 10,20,40,20,17] output should be sum is 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:

 A loop in programming is a way to repeat a set of instructions multiple times.


 It lets you run the same code over and over again without having to write multiple times.
 This is useful when you need to perform the same action on multiple items or repeat an action
until a certain condition is met.

Types of Loops in Python:

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.

The syntax of a for loop :

 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:

 range(5) generates a sequence of numbers from 0 to 4.


 i one by one takes each value in that sequence, and print(i) displays it on each iteration.

Ques 1 Write a program to print only even numbers in first n natural numbers.

Ques 2 Write a program to print sum of first n natural numbers.

Ques 3 Write a program to print product of first n natural numbers.


Ques 4 Write a program to calculate and print sum of odd numbers only in first n natural
numbers.

Ques 5 Write a program to print all numbers divisible by some number x in first n natural numbers.
range() function:

The range() function in Python generates a sequence of numbers.

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

range(m,n,z) : m to n-1 every zth element

(if z is negative it reverses the sequence)


Ques Write a program that prints 1 4 7 10 and so on upto nth
number.

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:

for loop allows you to go/iterate through each character in a tring..

Syntax:

 variable: A temporary name for the current character in the string


 string_name: The string to iterate through.

Q1 Program to print every character in a given string.

Q2 Program to print only vowels in a given string.


Q3 Program to calculate and print no of vowels in a given list.

Q4 Program to calculate and print sum of only even values in a given list.

Q4 Write a program to count the no of any given character in any string.


for loop with a list or tuple.:

A list is a collection of items enclosed in square brackets [ ].


A tuple is a collection of items enclosed in parentheses ( ).
The for loop allows you to go/iterate through each item in the list or tuple.

Syntax:

 variable: A temporary name for the current element in the list or tuple.
 list_name: The list to iterate through.

Q1 Program to print every element in a given list.

Q2 Program to print every odd element in a given list.


Q3 Program to calculate and print sum of all the elements in a given list.

Q4 Program to calculate and print sum of only even values in a given list.

Q6 Write a program to count the no of items in a given list.


Q7 Write a program to print all the strings starting from either R or S 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

 A logical expression that is checked before each iteration of the loop.


 If the condition is True, the loop executes; if False, the loop terminates.
 If the condition is always True, loops runs forever.

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 1: program to print first n natural numbers using while loop


Example 2: program to print first n numbers using while loop in reverse order

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

while loop with strings:

Example: count no of a’s in atring using while


while loop with lists/tuples:

Program to print Sum of list items using while.


In Python, the else block can be used with both for and while loops. It runs only when the loop
is not terminated by a break statement.

1.else with for loop

 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.

'hello' is the same as "hello".

To create a multiline string use triple quotes (''' or """) .

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.

str[0] - first character of string


str1[1] -- 2nd 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.

str[-1] -- last character of string

str[-2] ---- 2nd last character of string and so on.


Slicing of a string :
You can return a part of string by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part
of the string.

Syntax: str [ startindex: endindex]

Note:

End index is never included.

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[2:] Will start at index 2 to the end of string.

str[:5] Will start from the 0 index and end at index 5(not included)

str[:] It will give complete string.

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).

keep adding 2 to start index. 2,4,6,8,10,12

str[2:14:3] It will give every 3rd character starting at index 2 (included) and ending at index 9 (not included).

keep adding 3 to start index. 2,5,8,11

str[-8:-1:2] It will give every 2nd character starting at index -8 (included) and ending at index -1(not included).

keep adding 2 to start index. -8,-6,-4,-2

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.

a.)Using string directly b.)Using index and range()

Change any character in the string:

You can change the complete string e.g.


A = “hello world”
A = “python”

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

3. Membership operators with string: in , not in


String functions and methods:

1. upper() It returns the string into upper case.

2. lower() It returns the string into lower case.


3. isupper() Returns True if all characters in the string are upper case otherwise
returns False.

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

8. capitalize() Converts the first character of string to upper case


9. title()
Converts the first character of each word to upper case

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

13. replace() Replaces some specified charcter(s) with others 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.

You can specify the separator, default separator is any whitespace.


18 partition()
This method Searches for the given character(s) and return a tuple
with three elements:

1 - everything before the "match"


2 - the "match"
3 - everything after the "match"
List:
 Used to store multiple values in a single variable.
 List is mutable data type.
 List is ordered.
 Values in a list can be of any other data type.
 Duplicates are allowed.
 List items are indexed, the first item has index [0], the second item
has index [1] etc.

Creating a List : List is created using [ ] brackets.


list() constructor can also be used when creating a new list.
Examples:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3.5]
list3 = [True, False, False]
list4 = [11,12.5, "apple", "banana",7,True ]

Print a list:
To print a list use syntax: print(listname)
List Length :

Length of a list means no of items it has, use the len() function.

Syntax: len(listname)

Access List Items:


List items are indexed.
you can access them by using the index number with the list name.
First item has index zero.
Index 1 refers to 2nd item, index 2 refers to 3rd item and so on.

List[0] - first element


List1[1] -- 2nd element and so on

Negative Indexing
Negative index means to start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

List[-1] -- last item of list

List[-2] ---- 2nd last item of list and so on.

Look in the following example with the outputs:


Range of Index :

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.

Syntax: listname [ startindex, endindex]

Note:

End index is never included.


When no end index is provided, the range will go on to the end of the list
When no start index is provided, the range will start from the first item of the list

list1[2:5] It will start at index 2 (included) and end at index 5 (not included).

list1[2:] Will start at index 2 to the end of list.

list1[:5] Will start from the 0 index and end at index 5(not included)

list1[:] It will give complete list.

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).

keep adding 3 to start index. 2,5,8

list1[-8:-1:2] It will give every 2nd item starting at index -8 (included) and ending at index -1(not included).

keep adding 2 to start index. -8,-6,-4,-2

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:

a.)Using append() method b.) Using insert() method

append() will always add item to the end of a insert() method will insert an item at a specified
list. index.

Syntax: listname.append(item) Syntax: listname.insert(index,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’)

list2=[10,20,30,40] , add 50 at the end.


list2=[10,20,30,40] Add 50 at index 3.
list2.append(50)
list2.insert(3,50)
Looping a list:
We need to use a loop if we want to Get or print item one by one.

a.)Using directly b.)Using range()

Change an item in the list:


To change the value of a specific item, use its index number. E.g. if you want to change
1st item use index 0. If you want to change 3rd item, use index 2 etc.
Syntax: listname[index] = value
Removing Item from the list:
These two methods are used to remove items from a list:

a.)Using remove() method b.)Using pop() method

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)

Example 2: remove index 2 from the list2


Example 2: remove 30 from the list2
list2.pop(2)
list2.remove(‘cherry’)

Dictionary methods:
1. keys() : It returns a list containing all the keys of dictionary.

syntax
dictionary.keys()

Looping through a dictionary:


List functions and methods:

List1 = ["apple", "banana", "cherry" , "apple", "peach"]

List2 = [10,20,10,40,30,10,50]

1. count() It returns the number of times an item appear in a list. If doesn’t


exist it returns zero.

2. reverse() It reverses the original list.

3. max() It returns the highest value from a list


4. min() It returns the lowest value from a list.

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.

If no such value is found, error occurs.


7. extend()
This functions add all the elements of 2nd list to the first.
It can also add elements from a tuple or dictionary to the list.

lists with + operator:

There are several ways to join, or concatenate, two or more lists in Python.

List with * operator:

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.

Accessing value of a key:

a.)Using square brackets


Adding or Updating an item in a dictionary:
Adding and updating is done in a same way. If a key already exists then its value will be updated.
If a key doesn’t exist already ,then a new key:value pair is added to the dictionary.
There are two ways for doing so.

a.)Using square brackets b.)Using update() method

Updating a dictionary using update():


Updating a dictionary using square brackets :
In this case key already exists, so just its value is
In this case key already exists, so just its value is updated with the new one.
updated with the new one.
Example : you want to change the name to Ramesh
Example : you want to change the name to Ram
and marks to 89
and marks to 90
Removing Items
These two methods are used to remove items from a dictionary:

a.)Using pop() b.)Using popitem()

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.

3. items() : It returns a list of all the items (key:value pairs) 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:

del keyword is used to delete a complete dictionary, list or tuple.


When used with keyname, it can also delete the key:value pair from dictionary.

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.

Creating a Tuple : Tuple is created using ( ) brackets.


Tuple() constructor can also be used when creating a new Tuple.
Examples:
Tuple1 = ("apple", "banana", "cherry")
Tuple2 = (1, 5, 7, 9, 3.5)
Tuple3 = (True, False, False)
Tuple4 = (11,12.5, "apple", "banana",7,True )

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 :

Length of a Tuple means no of items it has, use the len() function.

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.

Tuple[0] - first element


Tuple1[1] -- 2nd element and so on

Negative Indexing

Negative index means to start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Tuple[-1] -- last item of Tuple

Tuple[-2] ---- 2nd last item of Tuple and so on.

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.

a.)Using directly b.)Using range()

Adding/Removing/changing Item from the Tuple:


You can not remove or add or change tuple items like a list.

T1=(10,20,30)
T1[1] = 40 #not allowed

Way of adding an item to a tuple is using + operator:


T1 = (10,20,30)
T1= T1+(40)
print(T1) #(10,20,30,40) Allowed
Tuple functions and methods:
1. count() It returns the number of times an item appear in a Tuple. If doesn’t exist it returns
zero.

2. max() max() returns the highest value from a Tuple


3. min() min() returns the lowest value from a Tuple

4. sorted() This function returns a list of sorted Tuple items in alphabetical or numerical order.
By default the order is ascending.

Use reverse=True if you want descending order.


5. index() The index() method returns the index of the first occurrence of the given value.

If no such value is found, error occurs.

6. sum ()
This functions returns the sum of all tuple items.
Tuples with + operator:

It is used to join two or more Tuples in Python.

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.

You might also like