0% found this document useful (0 votes)
4 views21 pages

Unit 2 Python Program class 11 chapter 2

The document provides an overview of programming languages, categorizing them into machine, assembly, high-level, fourth-generation, and fifth-generation languages, with examples for each. It also discusses language translators like compilers, interpreters, and assemblers, highlighting their differences. Additionally, it covers Python programming, including its features, limitations, execution modes, input functions, and the structure of a Python program, along with examples of simple Python programs.

Uploaded by

goelhasit2022
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)
4 views21 pages

Unit 2 Python Program class 11 chapter 2

The document provides an overview of programming languages, categorizing them into machine, assembly, high-level, fourth-generation, and fifth-generation languages, with examples for each. It also discusses language translators like compilers, interpreters, and assemblers, highlighting their differences. Additionally, it covers Python programming, including its features, limitations, execution modes, input functions, and the structure of a Python program, along with examples of simple Python programs.

Uploaded by

goelhasit2022
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

Python Program CBSE

Programming Language
A programming language is a language used by programmers to communicate with a
computer and create software, applications, and websites. E.g. Python, C, C++, Java,
JavaScript, PHP etc.

Types of Programming Languages

Programming languages can be classified into different types based on their level of
abstraction and programming style.

1. Machine Language (1GL)

Machine language is the lowest-level programming language that uses only binary digits
(0 and 1). It is directly understood by the computer.

2. Assembly Language (2GL)

Assembly language uses mnemonic instructions such as ADD, MOV, and SUB instead of
binary numbers. It is converted into machine language by an Assembler.

Example: MOV A, B

3. High-Level Language (3GL)

A high-level language is a user-friendly programming language that uses English-like


words. It is easy to learn and requires a Compiler or Interpreter to convert it into
machine language.

Examples: Python, C, C++, Java

4. Fourth-Generation Language (4GL)

A fourth-generation language is a high-level language used for database management,


report generation, and application development. It requires less coding than high-level
languages.

Examples: SQL, MATLAB

5. Fifth-Generation Language (5GL)

A fifth-generation language is a programming language mainly used for Artificial


Intelligence (AI) and expert systems. It focuses on solving problems using logic rather
than writing detailed instructions.

Examples: Prolog, Mercury

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Language Translator

A Language Translator is a system software that converts a program written in a


programming language (source code) into machine language (binary code) so that the
computer can understand and execute it.

Types of Language Translators

1. Compiler

A Compiler is a language translator that converts the entire program into machine
language at once before execution. If there are errors, they are displayed after the
compilation process.

Examples: C, C++, Go

2. Interpreter

An Interpreter is a language translator that converts and executes the program one line
at a time. It stops execution when an error is found.

Examples: Python, JavaScript, Ruby

3. Assembler

An Assembler is a language translator that converts an Assembly Language program


into Machine Language.

Example:

MOV A, B

ADD A, C

Difference Between Compiler and Interpreter

Compiler Interpreter

Translates the whole program at once. Translates one line at a time.

Executes the program after compilation. Executes the program line by line.

Faster execution. Slower execution.

Shows all errors together after compilation. Shows one error at a time and stops.

Creates an executable (.exe) file. Does not create an executable file.

Example: C, C++ Example: Python, JavaScript

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Python Program
Python is a high-level, interpreted, and general-purpose programming language that is
easy to learn and used for developing software, websites, games, data analysis, artificial
intelligence, and automation.
Overview of Python

• Python was created by Guido van Rossum.


• Python was first released in February 1991.
• The name Python was inspired by the British comedy television show "Monty
Python's Flying Circus", not the snake.
• Python supports both Procedural Programming and Object-Oriented
Programming (OOP).
• Python is free and open-source, so anyone can use, modify, and distribute it.
• Python is easy to learn because of its simple and readable syntax.
• Python is influenced by several programming languages, especially: ABC,
Modula-3

Features of Python

Python is one of the most popular programming languages because of its simplicity,
flexibility, and powerful features.

1. Easy to Learn

Python has a simple and easy-to-understand syntax, making it ideal for beginners.

2. Interpreted Language

Python executes code line by line without requiring compilation, making debugging
easier.

3. Free and Open-Source

Python is free to use, and its source code is available for anyone to modify and
distribute.

4. Platform Independent

Python programs can run on different operating systems such as Windows, Linux, and
macOS without major changes.

5. Dynamically Typed

There is no need to declare the data type of a variable. Python automatically determines
the data type during execution.

Example:

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

x = 10 #int

name = "Ram" #string

price = 99.5 #float

Limitations of Python

• Slower execution speed than compiled languages.


• Consumes more memory.
• Not suitable for mobile app development.
• Runtime errors due to dynamic typing.
• Limited support for low-level programming.

Execution Modes
Python programs can be executed in two modes:
1. Interactive Mode
Interactive mode allows you to write and execute Python statements one at a time. The
result is displayed immediately after each statement.
Features

• Executes one statement at a time.


• Gives immediate output.
• Useful for learning, testing, and debugging small pieces of code.
• Does not save the code automatically.

How to Open Python (IDLE)


1. Click the Start button.
2. Type IDLE (Python) in the search bar.
3. Click IDLE (Python 3.x) from the search results.
4. The Python Shell will open.
5. You can now start writing and running Python programs in Interactive Mode.

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

2. Scripting Mode
Scripting mode allows you to write a complete Python program in a file with the .py
extension and execute it later.
Features

• Programs are written in a Python file.


• Code is saved permanently.
• Suitable for large and complex programs.
• Easy to edit, reuse, and maintain.
How to Open Python in Script Mode (IDLE)
1. Click the Start button.
2. Search for IDLE (Python 3.x).
3. Open IDLE (Python 3.x).
4. Click File → New File.
5. A new editor window will open (Script Editor).
6. Write your Python program.
7. Click File → Save (or press Ctrl + S).
8. Save the file with a .py extension (e.g., [Link]).
9. Click Run → Run Module or press F5.
10. The output will appear in the Python Shell.

Difference Between Interactive Mode and Scripting Mode

Interactive Mode Scripting Mode

Executes one statement at a time. Executes the entire program.

Gives immediate output. Produces output after running the script.

Code is not saved automatically. Code is saved in a .py file.

Best for learning and testing. Best for developing complete applications.

Uses the Python Shell (>>>). Uses a Python editor or IDE (e.g., IDLE, VS
Code, PyCharm).

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Input () Function:
The input () function is used to accept data from the user during program execution. It
returns the entered value as a string, which can be converted to int () or float () when
numeric input is required.
Some simple program
1. Write a program to find the sum of two numbers.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum =", sum)

2. Write a program to find the average of three numbers.


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
average = (a + b + c) / 3
print("Average =", average)

3. Write a program to calculate the area of a rectangle.


length = float(input("Enter length: "))
breadth = float(input("Enter breadth: "))
area = length * breadth
print("Area =", area)

4. Write a program to calculate the perimeter of a rectangle.


length = float(input("Enter length: "))
breadth = float(input("Enter breadth: "))
perimeter = 2 * (length + breadth)
print("Perimeter =", perimeter)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

5. Write a program to calculate the area of a circle.


radius = float(input("Enter radius: "))
area = 3.14 * radius * radius
print("Area =", area)

6. Write a program to calculate simple interest.


p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))
si = (p * r * t) / 100
print("Simple Interest =", si)

7. Write a program to convert Celsius to Fahrenheit.


celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Fahrenheit =", fahrenheit)

8. Write a program to calculate the square of a number.


num = int(input("Enter a number: "))
square = num * num
print("Square =", square)

9. Write a program to calculate the cube of a number.


num = int(input("Enter a number: "))
cube = num * num * num
print("Cube =", cube)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

10. Write a program to swap two numbers using a third variable.


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
temp = a
a=b
b = temp
print("After swapping:")
print("a =", a)
print("b =", b)

Points to remember

1. Python is case-sensitive i.e. it will treat small letter and capital letter as two
different entities like m & M will be treated differently in Python.
2. We can use up arrow (↑) and down arrow (↓) to select previous command and
press enter to recall and execute.
3. Print statement is required only while working with script mode otherwise in
interactive mode values can be printed without print statement

Structure of a Python Program


A Python program is usually written in a step-by-step structure that makes it easy to
understand and execute. Just like an essay has an introduction, body, and conclusion, a
Python

program also has three main sections.

• Header / Comments: Used to describe program purpose.


• Body / Logic: Main code for processing input.
• Output Section: Displays the results.

Example:
# Program to display sum of two numbers
a = 10
b = 20
sum =a+b
print("Sum =", sum

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Python Character Set


A character set in Python means all the valid characters that can be used to form words,
identifiers, numbers, and symbols in a Python program.

Python Character Set Includes:

Letters

All uppercase (A–Z) and lowercase (a–z) English alphabets are allowed. Python treats
uppercase and lowercase as different (case-sensitive).

Example: sum and Sum are two different variables

Digits

All numbers from 0 to 9 can be used in Python programs. Digits are used in numeric
values or inside variable names (but variable names cannot start with a digit).

Special Symbols

Python supports various special characters and operators that are used for operations,
grouping, or separation. ( + - * / = % ( ) [ ] { } @ , : . ' " # < > _ )

White Spaces

White space characters include space, tab, newline, etc. Python uses indentation
(spaces or tabs) to define code blocks. So, white space is very important in Python.
(space, tab (\t), newline (\n))

Other Characters

Python also supports other characters such as: Escape characters (like \n, \t, \\) Unicode
characters (for international symbols, e.g. “ह”, “ü”, “é”)

print("Hello\nWorld") # \n adds a new line

print("नमस्ते") # Unicode tex

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Token in Python
A token is the smallest unit or building block of a Python program. Every word, number,
or symbol you write in Python code is a token. Python breaks each line of code into tokens
before understanding or executing it.

Python has five main types of tokens:

• Keywords
• Identifiers
• Literals (Constants)
• Punctuators (Separators / Delimiters)
• Operator

1. Keywords

Keywords are reserved words in Python that have a predefined meaning and purpose.
They are used to define the structure and flow of a Python program. Since they have
special meanings, they cannot be used as variable names, function names, or identifiers.

Examples: if, else, while, for, break, continue, True, False, import, def, class, return, try,
except, and, or, not, etc

2. Identifiers

Identifiers are the names given by the programmer to variables, functions, classes, or
objects. They help identify different elements in a Python program. An identifier must
begin with a letter or underscore (_) and cannot be a Python keyword.

Rules for Identifiers

1. Can use letters (A–Z, a–z), digits (0–9), and underscores (_).
2. Cannot start with a digit.
3. Cannot use special symbols (@, #, $, %, &, !, -, etc.) or spaces.
4. Cannot be a Python keyword (if, for, while, class, etc.).
5. Case-sensitive (Name, name, and NAME are different identifiers).

3. Literals (Constants)

Literals (Constants) are fixed values written directly in a Python program. They represent
constant data that does not change during the execution of the program.

Example:
age = 20
name = "Ram"

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Types of Literals in Python

1. String Literals

A String Literal is a sequence of characters enclosed within quotation marks. It is used


to store text such as names, messages, or sentences.

Python provides four types of string literals:

a. Single-Quoted String

A string enclosed in single quotation marks (' ') is called a single-quoted string. It is
commonly used for short text.

Example:

name = 'Ram'

print(name)

Output:

Ram

b. Double-Quoted String

A string enclosed in double quotation marks (" ") is called a double-quoted string. It
works the same as a single-quoted string.

Example:

city = "Kathmandu"

print(city)

Output:

Kathmandu

c. Triple Single-Quoted String

A string enclosed in three single quotation marks (''' ''') is called a triple single-quoted
string. It is used for multi-line strings or long text.

Example:
message = '''Welcome
to
Python'''
print(message)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

d. Triple Double-Quoted String

A string enclosed in three double quotation marks (""" """) is called a triple double-
quoted string. It is also used for multi-line strings and documentation (docstrings).

Example:
text = """Python is
easy to
learn."""
print(text)

Size (Length) of a String

The size (or length) of a string is the total number of characters present in the string. It
includes letters, digits, spaces, and special symbols. Python provides a built-in function
called len() to find the length of a string.

Example

text = "Hello World"

print(len(text))

2. Numeric Literals

Numeric literals are fixed numeric values written directly in a Python program. They are
used to represent numbers for mathematical calculations and other operations.

Python supports three types of numeric literals:

1. Integer (int)

2. Floating-point (float)

3. Complex (complex)

1. Integer Literals (int)

Integer literals are whole numbers without a decimal point. They can be positive,
negative, or zero.

Examples:

age = 20

temperature = -5

count = 0

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

2. Floating-Point Literals (float)

Floating-point literals are numbers with a decimal point. They are used to represent
fractional or real numbers.

Examples:

price = 99.99

pi = 3.14159

height = 5.8

3. Complex Literals (complex)

Complex literals are numbers that contain a real part and an imaginary part. The
imaginary part is represented using j.

Examples:

z1 = 2 + 3j

z2 = 5j

3. Boolean Literals

Boolean literals are fixed logical values used in a Python program. They represent the
result of a condition and have only two possible values: True and False. They are mainly
used in decision-making and conditional statements.

Examples:

age = 20

print(age >= 18)

print(age < 18)

4. Special Literal (None)

The None literal is a special value in Python that represents the absence of a value or no
value. It is used when a variable has not been assigned any value or when a function does
not return a value.

Example:
student = None
print(student)

Output:
None

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

5. Literal Collections

Literal collections are groups of values stored together in a single variable. They allow
multiple items to be stored and managed efficiently. Python provides four main collection
literals: List, Tuple, Set, and Dictionary.

1. List Literal

A List is an ordered and mutable (changeable) collection of items. It is enclosed in square


brackets [ ] and allows duplicate values.

Example

numbers = [10, 20, 30, 40]

print(numbers)

Output

[10, 20, 30, 40]

2. Tuple Literal

A Tuple is an ordered and immutable (unchangeable) collection of items. It is enclosed


in parentheses ( ) and allows duplicate values.

Example

colors = ("Red", "Green", "Blue")

print(colors)

Output

('Red', 'Green', 'Blue')

3. Set Literal

A Set is an unordered collection of unique items. It is enclosed in curly braces { } and does
not allow duplicate values.

Example

fruits = {"Apple", "Mango", "Orange"}

print(fruits)

Output

{'Apple', 'Mango', 'Orange'}

Note: The order of items in a set may be different each time you run the program.

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

4. Dictionary Literal

A Dictionary is a collection of key-value pairs. It is enclosed in curly braces { }, where each


key is associated with a value.

Example

student = {"Name": "Ram", "Age": 20}

print(student)

Output

{'Name': 'Ram', 'Age': 20}

4. Operators

Operators are special symbols that perform operations on variables and values. They are
used to perform arithmetic calculations, comparisons, assignments, and logical
operations in a Python program.

OR

An operator is a symbol that tells the computer to perform a specific mathematical or


logical operation on one or more values.

An operand is the value or variable on which an operator performs an operation. In other


words, operands are the data used by operators to produce a result.

For example:

a = 10

b=5

print (a + b)

(Here, + is a operator because it works on two operands , a and b.)

Types of Operators Based on Operands

1. Unary Operators → Work on one operand

2. Binary Operators → Work on two operands

1. Unary Operators

A unary operator performs an operation on a single operand. It is mainly used to represent


positive or negative numbers or to invert a logical value.

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

Examples:
a=5
print(-a) # Output: -5
print(+a) # Output: 5

2. Binary Operators

A binary operator operates on two operands to perform different types of operations like
addition, comparison, assignment, etc.

For example:

a = 10

b=5

print(a + b)

Types of Binary Operators

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numbers. They


are used for operations such as addition, subtraction, multiplication, division, and
finding the remainder.

Operator Meaning Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 5 2.0

% Modulus (Remainder) 10 % 3 1

// Floor Division 10 // 3 3

** Exponent (Power) 2 ** 3 8

Example

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
print("Addition =", a + b)

print("Subtraction =", a - b)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

print("Multiplication =", a * b)

print("Division =", a / b)

print("Modulus =", a % b)

print("Floor Division =", a // b)

print("Power =", a ** b)

2. Assignment Operators

Assignment operators are used to assign values to variables. They can also perform an
operation and assign the result to the same variable.

Operator Meaning Example

= Assign x = 10

+= Add and assign x += 5

-= Subtract and assign x -= 5

*= Multiply and assign x *= 2

/= Divide and assign x /= 2

%= Modulus and assign x %= 3

//= Floor divide and assign x //= 2

**= Power and assign x **= 2

Example

x = 10

x += 5

print(x)

x *= 2

print(x)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

3. Comparison (Relational) Operators

Comparison operators are used to compare two values or variables. They return a
Boolean value, either True or False, based on the comparison.

Operator Meaning Example

== Equal to 10 == 10

!= Not equal to 10 != 5

> Greater than 10 > 5

< Less than 5 < 10

>= Greater than or equal to 10 >= 10

<= Less than or equal to 5 <= 10

Example

a = 10

b=5

print(a == b)

print(a > b)

print(a <= b)

4. Logical Operators

Logical operators are used to combine or reverse conditions. They return True or False
depending on the logical relationship between conditions.

Operator Meaning Example

and Returns True if both conditions are True a>5 and b<10

or Returns True if at least one condition is True a>5 or b>10

not Reverses the result not(a>5)

Example

a = 10

b=5

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

print(a > 5 and b < 10)

print(a < 5 or b < 10)

print(not(a > 5))

5. Bitwise Operators

Bitwise operators are used to perform operations on the binary (bit) representation of
integers. They work on individual bits of a number.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT

<< Left Shift

>> Right Shift

Example

a=5 # Binary: 0101

b=3 # Binary: 0011

print("AND :", a & b)

print("OR :", a | b)

print("XOR :", a ^ b)

print("NOT :", ~a)

print("Left Shift :", a << 1)

print("Right Shift:", a >> 1)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

6. Membership Operators

Definition:
Membership operators are used to check whether a value exists in a sequence such as
a string, list, tuple, set, or dictionary. They return True or False.

Operator Meaning Example

in Value exists "a" in "Apple"

not in Value does not exist "z" not in "Apple"

Example

fruits = ["Apple", "Mango", "Orange"]

print("Apple" in fruits)

print("Banana" not in fruits)

7. Identity Operators

Identity operators are used to check whether two variables refer to the same object in
memory. They return True if both variables refer to the same object; otherwise, they
return False.

Operator Meaning Example

is Same object a is b

is not Different object a is not b

Example

a = [1, 2]

b=a

c = [1, 2]

print(a is b)

print(a is c)

print(a is not c)

Mr. Laukesh Jaishwal Class XI


Python Program CBSE

5. Punctuators (Separators/Delimiters)

Punctuators are special symbols used to separate, organize, and structure different parts
of a Python program. They help define the syntax of the program and improve code
readability.

Examples: (), [], {}, :, ,, .

Mr. Laukesh Jaishwal Class XI

You might also like