Programming with Python
Modern computers have the ability to follow generalized sets of operations
called programs. In simple words, a program is a sequence of
instructions that specifies how to perform a computation. These
programs allow computers to perform a wide range of tasks.
There are some specific languages which are used to write
programs. These languages are called programming languages.
Examples of some programming languages are Python, C, C++, LISP,
Java, PHP, etc.
Introduction to Python
Python was created by Guido van Rossum, and first released on
February 20, 1991. While you may know the python as a large snake, the
name of the Python programming language comes from an old BBC
television comedy sketch series called Monty Python's Flying Circus.
It is one of the most powerful high-level, open-source object-oriented
programming languages.Python is a dynamic, interpreted
(bytecode-compiled) language. There are no type declarations of
variables, parameters, functions, or methods in source code. This makes
the code short and flexible, and you lose the compile-time type checking
of the source code.It has huge libraries, frameworks and large community
support.
Applications of Python
There exist a wide variety of applications when it comes to Python. Some of the applications are:
140
PYTHON BASICS
Comments
Comments are the statements which are incorporated in the code to give a better understanding
of code statements to the user.
There are two types of comments in python.
1. Single Line
2. Multi Line
Single Line comment
A single-line comment is used to add some explanatory text in the program for better understanding
of the next line. A # sign is used to write a single line comment in the python program
For example,
# statement to add two numbers
res = 6 + 7
#Print the result
print(res)
Multiline comments
The multiline comments are written in python using triple quotes. You can write number lines
starting with triple quotes and end with triple quotes.
For example,
'''Write a python program to display the difference between two numbers, the first number should
be larger than second number'''
n1=5
n2=2
res=n1 - n2
print(res)
Keywords (Reserved Words)
Keywords are the reserved words or pre-defined words with a special meaning to the machine by
default. So the user cannot use them anywhere else or it cannot be changed or modified in the
entire program. They are always case-sensitive.
141
Identifiers
Identifiers are names used in programs to identify small units of programs such as variables,
objects, classes, functions etc.
Identifiers defined by the following few rules as follows:
1. It can be a combination of numbers and letters
2. It must start alphabets or underscore
3. Special characters are not allowed in identifiers name except underscore
4. Spaces are not allowed in identifier names, underscore can be used to separate two words
5. Upper Case and Lower Case letters are treated differently
Examples:
MyData, roll_no, year1 etc…
142
Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables
as a container that holds data which can be changed later throughout programming.
For example,
a=10
b=20
These declarations make sure that the program reserves memory for two variables with the names
a and b. The variable names stand for the memory location.
Note:
Assignment operator is used in Python to assign values to variables. For example, a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
Datatypes
In program, you have a choice to use any type of data such as real numbers, numbers with
decimals, numbers without decimals, text, etc. These type of data is defined by datatype in Python.
The python interprets the type of the variable according to the value stored in the variable. Follow
the below-given link to know more about data types.
143
Python Input and Output
We use the print() function to output data to the standard output device (screen). We can also
output data to a file.
An example is given below.
a = "Hello World!"
print(a)
The output of the above code will be: Hello World!
Example Code Output
a = 20 30
b = 10
print(a + b)
print(15 + 35) 50
print("My name is Alan") My name is Alan
name=”Alan” My name is Alan
print("My name is “,name)
n=5 I have 5 Apples !
print("I have",n,"Apples !")
144
input() function
The input() function is used to accept values from the user at runtime. This function accepts and
returns the text data by default. Therefore, you need to specify the data type if you want to use
numbers or any other datatype. This process is known as typecasting
Str = input(<String>) # Python expects the input to be of string datatype
Number = int(input(<string>)) # Input string gets converted to an integer value before assignment
Value = float(input(<String>)) # Input string gets converted to a decimal value before assignment.
Python Operators
Operators are special symbols which represent computation. They are applied on operand(s),
which can be values or variables. Same operators can behave differently on different data types.
Operators when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and Assignment operators.
Values and variables when used with operators are known as operands.
145
Conditional Statements
While coding in Python, sometimes we need to take decisions. For example, if a person needs to
create a calculator with the help of a Python code, he/she needs to take in 2 numbers from the
user and then ask the user about which function he/she wishes to operate. Now, according to the
user’s choice, the selection of function would change. In this case, we need the machine to
understand what should happen when. This is where conditional statements help.
Conditional statements help the machine in taking a decision according to the condition which gets
fulfilled. There exist different types of conditional statements in Python.
146
Some of them are:
Simple if Statement
If you have only one condition to be execute or one possibility of output, simple if statement is
useful for the same. Simple it executes the True condition block. Suppose, If gate is open you are
allowed to go inside!
Let’s see the syntax:
if <condition>:
statement(s)
Example:
gate_status = "open"
if gate_status=="open":
print("Entry is permitted")
if else statement
147
If else statement evaluates the test expression and will execute body of if only if the condition is
true . If the condition is false body of else will be executed .The blocks are separated using proper
indentation.
if <condition>:
statement(s)
else:
statement(s)
Observe the following code:
gate_status = "open"
if gate_status=="open":
print("Entry is permitted")
else:
print("You have to go back to your home, Bye - Bye")
if- elif- else ladder
Python if-elif-else ladder is used in the case when you have more than two choices or possibilities.
The elif is a short form of else if. The ladder means it will continue upto n possiblities.
The syntax for python ef-elif-else ladder is as following:
if <condition1>:
statement(s)
elif <condition2>:
statement(s)
elif <condition3>:
148
statement(s)
....
....
....
else:
statement(s)
Example :
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Python loops
149
Loops are a collection of statements executed repeatedly until the condition evaluates to false. It
is also known as iteration or iterative statements. It can be also considered as step by step
execution of python statements until the condition evaluates to false.
Types of Loop
Python support two kinds of loops.
1. While: A while loop is used when you have different repetitive statements with a single
condition. When the condition gets false, your loop will terminate itself. While loop may have
else block too quite often.
2. For: The easy and popular loop is for a loop. It is very easy to write and understand because
all the parts of loops are written in the same line in for loop. It will reduce the lines of codes
as three parts of loops are written in a single line.
while loop
The while syntax is as follows:
while <condition>:
statement(s)
update_statement
Observe this code which displays a series of numbers from 1 to 10.
150
i=1
while i<=10:
print(i)
i=i+1
print("End of loop")
For Loop
The for loop is used to execute the sequence of statements executed in a series. It is the most
popular loop among python developers. It is also work in a similar way as while loop is working.
Observe the syntax of for loop:
for <variable> in <sequence>:
body loop
So here variable is a variable from and then you can take a sequence to execute the statements.
The in operator is used to take check the value in the specified sequence.
For the sequence, you can use the range function.
The range() function takes three basic parameters. The first is a start, the second is a stop and the
third is a step.
range(start,stop,step)
for i in range(1,10,1):
print(i)
In the above code, the range function is used. Hence, the loop starts with 1, stops with 9 and taking
one step in every execution. The output will be 1 to 9 numbers only.
PYTHON PRACTICALS :
CLASS X LIST OF PRACTICALS 2022-23
SNO SIMPLE PROGRAMS
1 Display the message “Welcome to Python "
2 Print your School Address
3 Sum of 2 numbers
4 Sum and Average of 3 numbers
5 Area and perimeter of a circle
6 Square and Cube of a Number
7 Area and perimeter of a Rectangle
8 Calculate Percentage after inputting 5 marks
151
Python List
What is a List?
● Lists in Python are used to store collections of data within a single variable.
● A list is a collection which is ordered and changeable (mutable).
● Lists allow duplicate values.
● Lists are defined by placing elements inside square brackets [], separated by
commas.
Example:
# Create a list of integers
numbers = [10, 20, 30, 40]
# Create a list of strings
fruits = ["apple", "banana", "cherry"]
# Create a list containing different data types
mixed_list = ["apple", 42, True, 3.14]
List Indexing
● Elements in a list are accessed using an index.
● Indexing starts from 0 in Python.
● Negative indexing starts from the last element with -1.
Example:
fruits = ["apple", "banana", "cherry"]
# Access the first item (index 0)
print(fruits[0]) # Output: apple
# Access the last item using negative index
print(fruits[-1]) # Output: cherry
Modifying List Elements
● Lists are mutable, meaning you can change their content after creation.
● Modify an element by referencing its index.
Example:
fruits = ["apple", "banana", "cherry"]
# Change the second item
fruits[1] = "blueberry"
print(fruits) # Output: ["apple", "blueberry", "cherry"]
Adding Elements to a List
● append(): Adds an element at the end of the list.
● insert(): Adds an element at a specified index.
● extend(): Adds the elements of another list (or any iterable) to the end of the
current list.
Example:
fruits = ["apple", "banana"]
# Add "cherry" to the end
fruits.append("cherry")
print(fruits) # Output: ["apple", "banana", "cherry"]
# Insert "blueberry" at position 1
fruits.insert(1, "blueberry")
print(fruits) # Output: ["apple", "blueberry", "banana",
"cherry"]
# Extend the list with another list more_fruits = ["orange",
"mango"] fruits.extend(more_fruits) print(fruits) # Output:
["apple", "blueberry", "banana", "cherry", "orange", "mango"]
Removing Elements from a List
● remove(): Removes the first occurrence of a specified value.
● pop(): Removes the element at a specified index (or the last element if no index
is provided).
● del: Deletes an element at a specific index or the entire list.
● clear(): Removes all elements from the list.
Example:
fruits = ["apple", "banana", "cherry", "banana"]
# Remove the first occurrence of "banana"
fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry", "banana"]
# Pop the last element
popped_fruit = fruits.pop()
print(popped_fruit) # Output: banana
print(fruits) # Output: ["apple", "cherry"]
# Delete the first element
del fruits[0]
print(fruits) # Output: ["cherry"]
# Clear the entire list
fruits.clear()
print(fruits) # Output: []
List Slicing
● Lists can be sliced to create a new list containing a subset of elements.
● Slicing uses the syntax list[start:end], where start is inclusive and end
is exclusive.
Example:
numbers = [10, 20, 30, 40, 50]
# Slice from index 1 to 3
print(numbers[1:4]) # Output: [20, 30, 40]
# Slice from the beginning to index 2
print(numbers[:3]) # Output: [10, 20, 30]
# Slice from index 2 to the end
print(numbers[2:]) # Output: [30, 40, 50]
Looping Through a List
● You can loop through the items of a list using a for loop.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
List Comprehensions
● List comprehensions provide a concise way to create lists.
● They consist of an expression followed by a for clause, all enclosed in square
brackets.
Example:
# Create a list of squares
squares = [x**2 for x in range(6)]
print(squares) # Output: [0, 1, 4, 9, 16, 25]
Common List Methods
● len(list): Returns the number of elements in the list.
● list.sort(): Sorts the list in ascending order (or descending if
reverse=True is used).
● list.reverse(): Reverses the order of elements in the list.
● list.index(value): Returns the index of the first occurrence of the specified
value.
● list.count(value): Returns the number of times a specified value appears
in the list.
Example:
fruits = ["apple", "banana", "cherry", "apple"]
# Number of elements in the list
print(len(fruits)) # Output: 4
# Sort the list alphabetically
fruits.sort()
print(fruits) # Output: ["apple", "apple", "banana", "cherry"]
# Reverse the list
fruits.reverse()
print(fruits) # Output: ["cherry", "banana", "apple", "apple"]
# Find the index of "banana"
print(fruits.index("banana")) # Output: 1
# Count occurrences of "apple"
print(fruits.count("apple")) # Output: 2
PART-C: PRACTICAL WORK
UNIT 5: INTRODUCTION TO PYTHON: Suggested Program List
PRINT ● To print personal information like Name, Father’s Name, Class, School Name.
● To print the following patterns using multiple print commands-
● To find square of number 7
● To find the sum of two numbers 15 and 20.
● To convert length given in kilometers into meters.
● To print the table of 5 up to five terms.
● To calculate Simple Interest if the principle_amount = 2000 rate_of_interest = 4.5
time = 10
INPUT ● To calculate Area and Perimeter of a rectangle
● To calculate Area of a triangle with Base and Height
● To calculating average marks of 3 subjects
● To calculate discounted amount with discount %
● To calculate Surface Area and Volume of a Cuboid
● Create a list in Python of children selected for science quiz with following names-
LIST Arjun, Sonakshi, Vikram, Sandhya, Sonal, Isha, Kartik
Perform the following tasks on the list in sequence-
○ Print the whole list
○ Delete the name “Vikram” from the list
○ Add the name “Jay” at the end
○ Remove the item which is at the second position.
● Create a list num=[23,12,5,9,65,44]
○ print the length of the list
○ print the elements from second to fourth position using positive indexing
○ print the elements from position third to fifth using negative indexing
● Create a list of first 10 even numbers, add 1 to each list item and print the final list.
● Create a list List_1=[10,20,30,40]. Add the elements [14,15,12] using extend
function. Now sort the final list in ascending order and print it.
● Program to check if a person can vote
IF, ● To check the grade of a student
FOR, ● Input a number and check if the number is positive, negative or zero and display an
WHILE appropriate message
● To print first 10 natural numbers
● To print first 10 even numbers
● To print odd numbers from 1 to n
● To print sum of first 10 natural numbers
● Program to find the sum of all numbers stored in a list
417 – Artificial Intelligence Class IX – 2024-2025 Page 10 of 15