0% found this document useful (0 votes)
15 views50 pages

Unit Wise Notes

B tech 3rd year students unit wise syllabus

Uploaded by

royk95952
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)
15 views50 pages

Unit Wise Notes

B tech 3rd year students unit wise syllabus

Uploaded by

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

Department of Computer Science & Engineering

Unit I

Introduction: Why Program, Hardware Overview, Python as a Language

Unit II

Installing and Using Python: Installing Python and Writing A Program, Writing Paragraphs of

Code, Doing the "Hello World" Assignment

Unit III

Variables and Expressions: Declaring variables, working with data types and variables, working

with numeric data, working with string data, Expression

Unit IV

Conditional Code and Decision: Conditional Statements, Defining and writing decision

statements, Illustrative programs Loops and Iteration: Loops and iteration, defining loops,

working with recursion, Illustrative programs.

Unit V

Functions: Define and use functions and modules, recursive functions, Illustrative programs
Department of Computer Science & Engineering

B.Tech Third Year Fifth Semester


Subject:-Python Programming (Open Elective)
Unit I

Why Program

Programming is one of the most powerful tools in the modern world, playing a vital role in

technology, science, business, and virtually every industry. Understanding why programming is

important involves recognizing its profound impact on our lives, as well as the unique

opportunities it offers for creativity, problem-solving, and career growth.

1. Solving Problems and Building Solutions

At its core, programming is about solving problems. Programmers create software that addresses

real-world challenges—whether it's designing apps that improve communication, algorithms that

predict market trends, or systems that streamline complex operations. Learning to program

allows individuals to think logically and break down large tasks into smaller, manageable pieces.

2. Automation and Efficiency

Programming enables the automation of repetitive tasks, freeing up time for more meaningful

work. From automating data entry to creating scripts that perform complex calculations, coding

allows businesses and individuals to boost productivity and reduce human error. In a world

driven by data and speed, these efficiencies are invaluable.

3. Innovation and Creativity

Programming provides a platform for creativity. It allows you to build anything from mobile

apps and websites to interactive games and advanced AI models. The only limit is your
Department of Computer Science & Engineering
imagination. By writing code, you can bring ideas to life in a tangible form, whether it's

developing the next breakthrough in technology or creating digital art.

4. Career Opportunities

The demand for programming skills has skyrocketed, with software development being one of

the fastest-growing professions globally. Knowledge of coding is essential in tech careers, but it

is also increasingly valuable in fields like healthcare, finance, and media. Mastering

programming opens up a vast array of career opportunities, often with high earning potential and

flexibility.

5. Understanding the Digital World

In a world where technology is embedded in nearly every aspect of life, learning to program

helps you understand how things work behind the scenes. From social media algorithms to smart

home devices, programming knowledge gives you insight into the technology shaping the

modern world and empowers you to take control of it.

6. Empowerment and Independence

Learning to program offers a sense of empowerment. You no longer rely on others to bring your

ideas to fruition; instead, you have the tools to build them yourself. Whether you're creating your

own startup, freelancing, or contributing to open-source projects, programming can foster

independence and self-sufficiency.

Hardware Overview

Hardware refers to the physical components of a computer system that are essential for its

operation. These components work together to execute tasks and run software, making the
Department of Computer Science & Engineering
overall system functional. Understanding the key elements of computer hardware provides

insight into how computers process information, store data, and interact with external devices.

1. Central Processing Unit (CPU)

The CPU, often called the "brain" of the computer, is responsible for executing instructions from

programs. It performs basic arithmetic, logic, control, and input/output (I/O) operations specified

by the instructions. The CPU typically consists of multiple cores, each capable of processing

tasks in parallel to increase efficiency. Faster CPUs enable computers to run complex programs

and handle multiple tasks simultaneously.

2. Memory (RAM)

Random Access Memory (RAM) is the temporary storage used by the CPU to store data that is

actively being used or processed. RAM allows for quick read and write access, which speeds up

data handling during program execution. The more RAM a system has, the better it can handle

large files and multitasking.

3. Storage

Computer systems require long-term storage to save data and applications. There are two main

types of storage:

 Hard Disk Drives (HDD): These use spinning disks to store data magnetically. HDDs

offer large capacities at a lower cost but are slower than SSDs.

 Solid-State Drives (SSD): SSDs use flash memory to store data electronically, offering

much faster read/write speeds and durability compared to HDDs. SSDs are becoming the

standard for modern computers, especially for operating system installations.

4. Motherboard
Department of Computer Science & Engineering
The motherboard is the main circuit board that connects all of the computer's hardware

components. It houses the CPU, RAM, storage devices, and other components like the graphics

card. It also provides the pathways for data to travel between the different parts of the computer.

The motherboard includes essential ports for connecting external devices like USBs, monitors,

and network cables.

5. Power Supply Unit (PSU)

The power supply unit converts electrical power from an outlet into usable power for the

internal components of the computer. Different components require varying amounts of power,

and the PSU ensures a stable supply, providing the necessary voltage and current to the CPU,

motherboard, storage devices, and peripherals.

6. Graphics Processing Unit (GPU)

The GPU, or graphics card, is responsible for rendering images, video, and animations. It is

particularly important for tasks like video editing, gaming, and 3D rendering, where visual

processing demands are high. GPUs come in two forms: integrated (built into the CPU) and

discrete (a separate component). Discrete GPUs are more powerful and are necessary for high-

performance graphics applications.

7. Input and Output Devices

 Input devices include peripherals like keyboards, mice, microphones, and scanners,

which allow the user to interact with the computer.

 Output devices display or transmit data from the computer to the user. Examples include

monitors, printers, and speakers. Both input and output devices connect to the

motherboard, enabling communication between the user and the machine.


Department of Computer Science & Engineering
8. Cooling Systems

Computers generate heat during operation, particularly from the CPU and GPU. Cooling

systems, including fans and heat sinks, help dissipate this heat to prevent overheating and ensure

smooth performance. Advanced systems may use liquid cooling for better efficiency, especially

in high-performance machines like gaming rigs or servers.

9. Network Interface Cards (NIC)

Network interface cards allow computers to connect to a network (local or internet) through

wired or wireless connections. A NIC can be built into the motherboard or installed as a separate

card. Modern systems often use Ethernet for wired connections and Wi-Fi for wireless

connectivity.

10. Peripheral Devices

Peripheral devices are external devices connected to the computer, expanding its functionality.

These include:

 Printers: For producing physical copies of digital documents.

 External storage: USB drives or external hard drives for additional or portable data

storage.

 Audio devices: Headphones, microphones, and speakers enhance multimedia

experiences.

Python as a Language

Python is a high-level, general-purpose programming language known for its simplicity,

readability, and versatility. It has become one of the most popular languages across many fields,
Department of Computer Science & Engineering
from web development to scientific computing, machine learning, data analysis, and automation.

Below are the key aspects that make Python stand out as a programming language:

1. Ease of Learning and Readability

Python’s syntax is designed to be clear and concise, resembling natural language. This makes it

an ideal language for beginners and experienced developers alike. Code written in Python is

typically easier to read and maintain compared to other languages, allowing developers to focus

more on solving problems rather than dealing with complex syntax.

Example:

# Simple Python code to print "Hello, World!"

print("Hello, World!")

2. Interpreted Language

Python is an interpreted language, which means that code is executed line by line, without the

need for compiling it beforehand. This allows for quick testing, debugging, and iteration, making

it an excellent choice for rapid development.

3. Cross-Platform Compatibility

Python is cross-platform, meaning it can run on different operating systems such as Windows,

macOS, and Linux without requiring modifications to the code. This flexibility makes Python a

go-to choice for developers who need to create software that works on multiple platforms.

4. Extensive Libraries and Frameworks

One of Python's greatest strengths is its vast ecosystem of libraries and frameworks. Whether

you're working on data analysis, web development, machine learning, or automation, there’s a

library for almost every need:


Department of Computer Science & Engineering
 Web Development: Frameworks like Django and Flask make building websites and

APIs straightforward.

 Data Science: Libraries such as Pandas, NumPy, and Matplotlib help with data

manipulation and visualization.

 Machine Learning: Libraries like TensorFlow, PyTorch, and scikit-learn provide

powerful tools for building AI and ML models.

 Automation: Tools like Selenium and Scrapy allow you to automate web scraping,

testing, and other repetitive tasks.

5. Object-Oriented and Functional Programming

Python supports multiple programming paradigms, including object-oriented programming

(OOP) and functional programming. This means developers can choose the approach that best

suits their project. Python’s OOP model is particularly useful for organizing and managing

complex code, while its support for functional programming allows for writing concise, elegant

code using functions and higher-order programming concepts.

Example of a Python class (OOP):

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print(f"{self.name} is barking!")
Department of Computer Science & Engineering

my_dog = Dog("Buddy", 5)

my_dog.bark()

6. Large Community and Support

Python has a massive and active community of developers who contribute to its ecosystem. This

community-driven nature means that Python has abundant tutorials, documentation, forums, and

third-party libraries. If you encounter a problem or need help with a specific task, it's likely that

someone has already solved it, and resources are readily available online.

7. Dynamic Typing and Flexibility

Python is dynamically typed, meaning you don’t need to declare the type of a variable when you

write code. This flexibility allows for quicker development, though it can also introduce bugs

that wouldn’t occur in statically typed languages. For example, Python automatically figures out

the type of a variable based on the value you assign to it.

Example:

x = 10 # x is an integer

x = "Hello" # Now x is a string

8. Versatile Use Cases

Python’s versatility makes it a top choice in a wide range of domains:

 Web Development: Frameworks like Django and Flask simplify building secure,

scalable web applications.

 Data Science: Python’s popularity in data analysis and machine learning is driven by

libraries like Pandas, NumPy, and TensorFlow.


Department of Computer Science & Engineering
 Scripting and Automation: Python is commonly used for writing scripts to automate

repetitive tasks, such as managing files, web scraping, or running scheduled jobs.

 Scientific Computing: Python is widely used in scientific research, thanks to its libraries

that support numerical computation, data visualization, and simulations.

 Game Development: Python, along with frameworks like Pygame, is used for creating

simple 2D games.

9. Strong Support for Integration

Python easily integrates with other languages like C, C++, Java, and JavaScript. This makes it

possible to use Python in systems where high performance is required, and certain portions of the

code need to be written in a lower-level language for speed. It also facilitates the development of

large-scale systems where multiple languages are used.

10. Community-Driven and Open Source

Python is open-source, meaning it is free to use and distribute. Its development is governed by a

global community, and contributions come from developers around the world. Python’s open-

source nature ensures that it continues to evolve and stay relevant in the ever-changing landscape

of programming languages.
Department of Computer Science & Engineering

B.Tech Third Year Fifth Semester


Subject:-Python Programming (Open Elective)
Unit II

Installing Python and Writing A Program

To get started with Python, you’ll need to install it on your computer and write your first

program. Here’s a step-by-step guide on how to install Python and write a simple program.

1. Installing Python

1. Download Python:

o Visit the official Python website: https://www.python.org/downloads/

o Download the latest version of Python by clicking on the button that says

"Download Python X.X.X."

2. Run the Installer:

o Open the downloaded file to begin the installation.

o During installation, make sure to check the box that says "Add Python to

PATH." This ensures you can run Python from the command line.

3. Complete the Installation:

o Click "Install Now" and follow the prompts. Once installed, Python is ready to

use.

Once Python is installed, you can use the Python IDLE to run Program.

1. Open the IDLE and type Python code directly:


Department of Computer Science & Engineering
print("Hello, World!")

This opens the Python interpreter.

2. Save it as hello.py.

Extension for save the python file is .py

3. Press F5 or Select RUN and the output will appear instantly:

Hello, World!

Writing Paragraphs of Code

Hello World

This is the simplest Python program that prints a string to the console.

print("Hello, World!")

Explanation: The print() function outputs text to the console.

Variables

Declaring an Integer Variable

# Declaring a variable with an integer value

age = 25

# Output the value of the variable

print(age)

Explanation:

 age is a variable that holds the value 25.


Department of Computer Science & Engineering
 In Python, you don't need to declare the type of the variable (like int for integer), as

Python automatically detects it based on the value assigned.

there are several rules and best practices you need to follow:

1. Valid Names

 Variable names must begin with a letter (a-z, A-Z) or an underscore (_).

 The rest of the variable name can include letters, digits (0-9), or underscores.

 Variable names cannot start with a digit.

valid_var = 10 # valid

_anotherVar = 20 # valid

2ndVar = 30 # invalid (starts with a digit)

2. Case Sensitivity

 Variable names are case-sensitive, meaning age, Age, and AGE are considered different

variables.

age = 25

Age = 30

AGE = 35

3. No Reserved Keywords

 You cannot use Python keywords (reserved words) as variable names. Examples of

keywords include if, else, while, for, class, def, return, etc.

You can check reserved keywords using the keyword module:

import keyword

print(keyword.kwlist)
Department of Computer Science & Engineering
4. Avoid Special Characters

 Variable names cannot include special characters such as !, @, #, $, %, etc..

my$var = 100 # invalid

5. No Spaces

 Spaces are not allowed in variable names. Use underscores (_) or camelCase to combine

words.

my variable = 50 # invalid (spaces not allowed)

my_variable = 50 # valid (snake_case)

myVariable = 50 # valid (camelCase)

6. Assignment

 Variables are assigned using the = operator.

x=5

y = "Hello"

7. Dynamic Typing

 Python is dynamically typed, meaning variables do not need an explicit type declaration.

A variable's type is determined by its assigned value.

a = 10 # Integer

a = "Now a string" # String (same variable with a different type)

8. Descriptive Names (Best Practice)

 Choose descriptive names to make your code more readable.

score = 100 # Descriptive

x = 100 # Less descriptive


Department of Computer Science & Engineering
9. Multiple Assignments

 You can assign values to multiple variables in one line.

x, y, z = 1, 2, 3 # Multiple assignment

a=b=c=0 # Same value to multiple variables

Data Types

 Numbers:

Numeric values are stored in numbers. The whole number, float, and complex qualities

have a place with a Python Numbers data type.

 Int:
Department of Computer Science & Engineering
Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and

so on. An integer can be any length you want in Python. It’s worth has a place

with int.

 Float:

Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to

within 15 decimal places.

 Complex:

An intricate number contains an arranged pair, i.e., x + iy, where x and y signify

the genuine and non-existent parts separately. The complex numbers like 2.14j,

2.0 + 2.3j, etc.

 Sequence Type :

 String :

The sequence of characters in the quotation marks can be used to describe the

string. A string can be defined in Python using single, double, or triple quotes.

 Lists :

Lists in Python are like arrays in C, but lists can contain data of different types.

The things put away in the rundown are isolated with a comma (,) and encased

inside square sections [].

To gain access to the list's data, we can use slice [:] operators. Like how they

worked with strings, the list is handled by the concatenation operator (+) and the

repetition operator (*).


Department of Computer Science & Engineering
 Tuple :

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of

items from various data types. A parenthetical space () separates the tuple's

components from one another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only

data structure.

 Dictionary :

A dictionary is a key-value pair set arranged in any order. It stores a specific value for

each key, like an associative array or a hash table. Value is any Python object, while the

key can hold any primitive data type.The comma (,) and the curly braces are used to

separate the items in the dictionary.

 Boolean :

True and False are the two default values for the Boolean type. These qualities are

utilized to decide the given assertion valid or misleading. The class book indicates this.

False can be represented by the 0 or the letter "F," while true can be represented by any

value that is not zero.

 Set :

The data type's unordered collection is Python Set. It is iterable, mutable(can change after

creation), and has remarkable components. The elements of a set have no set order; It

might return the element's altered sequence. Either a sequence of elements is passed

through the curly braces and separated by a comma to create the set or the built-in

function set() is used to create the set. It can contain different kinds of values.
Department of Computer Science & Engineering
# Simple Python Data Types Program

# Integer
x = 10
print("Integer:", x)

# Float
y = 10.5
print("Float:", y)

# String
name = "Alice"
print("String:", name)

# Boolean
is_valid = True
print("Boolean:", is_valid)

# List (A collection of items)


numbers = [1, 2, 3, 4, 5]
print("List:", numbers)

# Tuple (An immutable collection of items)


coordinates = (10, 20)
print("Tuple:", coordinates)

# Dictionary (A collection of key-value pairs)


person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print("Dictionary:", person)

# Set (A collection of unique items)


unique_numbers = {1, 2, 3, 3, 4, 5}
print("Set:", unique_numbers)
Department of Computer Science & Engineering
Operators

1. Arithmetic Operators

Used for mathematical operations like addition, subtraction, etc.

Operator Operation Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus (remainder) x % y

** Exponentiation x ** y

// Floor Division x // y
Department of Computer Science & Engineering

x = 10

y=3

print(x + y) # 13

print(x - y) # 7

print(x * y) # 30

print(x / y) # 3.3333

print(x % y) # 1 (remainder of 10/3)

print(x ** y) # 1000 (10^3)

print(x // y) # 3 (floor division, discards remainder)

2. Comparison Operators

Used to compare two values, returning True or False.

Operator Operation Example

== Equal to x == y

!= Not equal to x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Department of Computer Science & Engineering
x = 10

y=3

print(x == y) # False

print(x != y) # True

print(x > y) # True

print(x < y) # False

print(x >= y) # True

print(x <= y) # False

3. Logical Operators

Used to combine conditional statements.

Operator Operation Example

and True if both conditions are True x > y and x < 20

or True if at least one condition is True x > y or y > 5

not Inverts the condition (True to False, False to True) not x == y

x = 10

y=3

print(x > 5 and y < 5) # True (both are true)

print(x > 10 or y < 5) # True (second is true)

print(not x == y) # True (because x is not equal to y)

4. Assignment Operators
Department of Computer Science & Engineering
Used to assign values to variables.

Operator Operation Example

= Assign value x = 10

+= Add and assign x += 5

-= Subtract and assign x -= 5

*= Multiply and assign x *= 5

/= Divide and assign x /= 5

%= Modulus and assign x %= 5

**= Exponent and assign x **= 5

//= Floor divide and assign x //= 5

x = 10

x += 5 # x = x + 5, so x becomes 15

print(x) # 15

x *= 2 # x = x * 2, so x becomes 30

print(x) # 30

5. Bitwise Operators

These operate on bits and perform bit-by-bit operations.

Operator Operation Example

& AND x&y


Department of Computer Science & Engineering

Operator Operation Example

` ` OR

^ XOR x^y

~ NOT ~x

<< Left Shift x << 2

>> Right Shift x >> 2

x = 5 # Binary: 0101

y = 3 # Binary: 0011

print(x & y) # 1 (0101 & 0011 = 0001)

print(x | y) # 7 (0101 | 0011 = 0111)

print(x ^ y) # 6 (0101 ^ 0011 = 0110)

print(~x) # -6 (Bitwise NOT of 0101 becomes 1010 in 2's complement)

print(x << 1) # 10 (Shifts 0101 to 1010)

print(x >> 1) # 2 (Shifts 0101 to 0010)


Department of Computer Science & Engineering

Doing the "Hello World" Assignment

1. Open the IDLE and type Python code directly:

print("Hello, World!")

This opens the Python interpreter.

2. Save it as hello.py.

Extension for save the python file is .py

3. Press F5 or Select RUN and the output will appear instantly:

Hello, World!

Explanation:

 print() is a built-in Python function that outputs text to the console.

 "Hello, World!" is a string of text, and when passed into the print() function, it

gets displayed on the screen.


Department of Computer Science & Engineering

B.Tech Third Year Fifth Semester


Subject:-Python Programming (Open Elective)
Unit III

Variables and Expressions: Declaring variables, working with data types and variables, working

with numeric data, working with string data, Expression

Variables:

A variable is a symbol or name that stands for a value, which can change. Variables are like
containers that store information. In programming, variables are used to store data, while in
mathematics, they typically represent unknown or changing values.

 Example in Math:
o Let x=5. Here, x is a variable that holds the value 5.
 Example in Programming (Python):

x = 5

In Python, variables are used to store data values. Unlike some programming languages, Python
does not require you to declare the variable type explicitly; it is dynamically typed, meaning you
can change the type of the data stored in a variable at any time. Here’s a brief overview of how
to work with variables in Python:

Creating Variables

You can create a variable by assigning a value to it using the = operator.

# Examples of variable assignments


x = 5 # Integer
name = "Alice" # String
height = 5.6 # Float
is_student = True # Boolean

Variable Naming Rules

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


 Can contain letters, numbers (0-9), and underscores.
 Cannot start with a number.
 Case-sensitive (e.g., age and Age are different variables).
 Cannot use Python keywords (like if, for, while, etc.) as variable names.
Department of Computer Science & Engineering
Dynamic Typing

You can change the type of a variable by simply assigning a new value.

age = 25 # age is an integer


age = "twenty-five" # age is now a string

Multiple Assignments

You can assign values to multiple variables in a single line.

a, b, c = 1, 2, 3 # a = 1, b = 2, c = 3

Constants

While Python doesn’t have a built-in constant type, by convention, constants are defined using
uppercase letters.

PI = 3.14159

Checking Variable Type

You can check the type of a variable using the type() function.

print(type(x)) # Output: <class 'int'>


print(type(name)) # Output: <class 'str'>

Deleting Variables

You can delete a variable using the del statement.

del x # This deletes the variable x

Example Usage

Here’s a simple example of using variables in a program:

# Defining variables
name = "Alice"
age = 30

# Outputting a message
print(f"{name} is {age} years old.")
Department of Computer Science & Engineering

Working with data types and variables

Declaration of Variables

In Python, you declare a variable simply by assigning it a value. You don’t need to specify a data
type; Python infers it from the assigned value.

Example:

# Variable declaration
x = 10 # x is an integer
name = "Alice" # name is a string
price = 19.99 # price is a float

Re-declaration of Variables

You can redeclare a variable by assigning a new value to it. The new value can be of a different
type from the previous value.

Example:

# Redeclaring variable
x = 10 # x is initially an integer
print(x) # Output: 10

x = "Hello" # x is now a string


print(x) # Output: Hello

In Python, you can declare variables without explicitly specifying their data types. Python uses
dynamic typing, meaning that the type of a variable is inferred from the value it is assigned.
Here’s a quick overview of common data types in Python and examples of how to declare
variables:

1. Numeric Types

 Integer: Whole numbers.


 Float: Decimal numbers.
 Complex: Numbers with real and imaginary parts.

# Integer
age = 25

# Float
height = 5.9
Department of Computer Science & Engineering

# Complex
complex_num = 2 + 3j

2. String

A sequence of characters enclosed in quotes.

name = "Alice"
greeting = 'Hello, World!'

3. Boolean

Represents True or False.

is_student = True
is_employed = False

4. Sequence Types

 List: An ordered, mutable collection of items.


 Tuple: An ordered, immutable collection of items.

# List
fruits = ['apple', 'banana', 'cherry']

# Tuple
coordinates = (10.0, 20.0)

5. Set

An unordered collection of unique items.

unique_numbers = {1, 2, 3, 4, 5}

6. Dictionary

A collection of key-value pairs.

person = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}

7. NoneType
Department of Computer Science & Engineering
Represents the absence of a value.

value = None

Summary

 Variables in Python do not require explicit type declaration.


 The type is determined by the value assigned to the variable.
 Use the type() function to check the data type of a variable:

print(type(age)) # Output: <class 'int'>


print(type(name)) # Output: <class 'str'>

Working with numeric data

Basic Data Types

Python supports several numeric data types:

 Integers (int): Whole numbers, both positive and negative (e.g., 5, -10).
 Floating-point numbers (float): Numbers with decimal points (e.g., 3.14, -0.001).
 Complex numbers (complex): Numbers with a real and imaginary part (e.g., 3 + 4j).

# Example of numeric types


a = 5 # integer
b = 3.14 # float
c = 2 + 3j # complex

print(type(a), type(b), type(c))

Basic Arithmetic Operations

You can perform arithmetic operations on numeric types using standard operators:

 Addition: +
 Subtraction: -
 Multiplication: *
 Division: / (returns a float)
 Integer Division: // (returns an integer)
 Modulus: % (returns the remainder)
 Exponentiation: ** (raises to a power)
Department of Computer Science & Engineering
a = 10
b=5
addition = a + b # 15
subtraction = a - b # 5
multiplication = a * b # 50
division = a / b # 2.0

Working with string data

Working with string data in Python involves using various operations and methods to manipulate
and analyze strings. Here's a comprehensive overview of string handling in Python, complete
with explanations and examples.

1. Creating Strings

You can create strings using single quotes ('), double quotes ("), or triple quotes (''' or """) for
multi-line strings.

# Single line string


single_line = 'Hello, World!'

# Double line string


double_line = "Hello, World!"

# Multi-line string
multi_line = '''This is a multi-line
string that spans multiple
lines.'''

2. Accessing Characters

You can access individual characters in a string using indexing, where the index starts from 0.

my_string = "Python"
first_char = my_string[0] # 'P'
last_char = my_string[-1] # 'n'

3. String Length

Use the len() function to get the length of a string.

length = len(my_string) # 6

4. String Slicing
Department of Computer Science & Engineering
You can extract parts of a string using slicing.

substring = my_string[1:4] # 'yth'

5. String Concatenation

You can combine strings using the + operator.

greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!" # 'Hello, Alice!'

6. String Formatting

Python offers several ways to format strings:

 f-strings (formatted string literals) - Available in Python 3.6 and later:

age = 30
formatted_string = f"My name is {name} and I am {age} years old." # 'My name
is Alice and I am 30 years old.'

 str.format() method:

formatted_string = "My name is {} and I am {} years old.".format(name, age)

 Percent formatting (older method):

formatted_string = "My name is %s and I am %d years old." % (name, age)

7. Common String Methods

Python provides many built-in string methods for manipulating strings. Here are some
commonly used ones:

 upper() and lower(): Convert to uppercase or lowercase.

upper_case = my_string.upper() # 'PYTHON'


lower_case = my_string.lower() # 'python'

 strip(): Remove leading and trailing whitespace.

whitespace_string = " Hello, World! "


stripped_string = whitespace_string.strip() # 'Hello, World!'
Department of Computer Science & Engineering
 split(): Split a string into a list based on a delimiter.

sentence = "This is a sentence."


words = sentence.split() # ['This', 'is', 'a', 'sentence.']

 join(): Join a list of strings into a single string with a delimiter.

word_list = ['This', 'is', 'joined.']


joined_string = ' '.join(word_list) # 'This is joined.'

 replace(): Replace a substring with another substring.

new_string = my_string.replace('Py', 'Pyton') # 'Python'

8. Checking Substrings

You can check if a substring exists within a string using the in keyword.

contains_python = "Py" in my_string # True

9. String Immutability

Strings in Python are immutable, meaning that once a string is created, it cannot be changed.
Operations that modify strings will return a new string instead of modifying the original.

original_string = "Hello"
new_string = original_string.replace('H', 'J') # 'Jello'
# original_string is still 'Hello'

10. Escape Characters

To include special characters in strings, you can use escape characters, like \n for a new line, \t
for a tab, and \\ for a backslash.

escaped_string = "First line.\nSecond line."

Expression

In Python, an expression is a piece of code that evaluates to a value. Expressions can be as


simple as a single value or variable, or they can be more complex, involving operators and
function calls. Here are some key points to understand about expressions in Python, along with
examples:
Department of Computer Science & Engineering
1. Simple Expressions

 Literals: A literal is a fixed value in your code.

42 # An integer literal
3.14 # A float literal
"Hello" # A string literal

 Variables: A variable is a named storage location that can hold a value.

x = 10 # x is a variable holding the integer value 10

2. Arithmetic Expressions

These expressions involve arithmetic operators and evaluate to a numeric value.

result = 5 + 3 * 2 # Evaluates to 11 (multiplication has higher precedence)

 Operators: Common arithmetic operators include +, -, *, /, // (floor division), %


(modulus), and ** (exponentiation).

3. Comparison Expressions

These expressions compare two values and return a boolean value (True or False).

is_greater = 10 > 5 # Evaluates to True


is_equal = (10 == 10) # Evaluates to True

 Operators: Common comparison operators include ==, !=, >, <, >=, and <=.

4. Logical Expressions

Logical expressions combine boolean values using logical operators and return a boolean value.

is_true = (10 > 5) and (5 < 20) # Evaluates to True


is_false = (10 > 5) or (5 > 20) # Evaluates to True

 Operators: The logical operators are and, or, and not.

5. Compound Expressions

These can combine multiple types of expressions together.

x = 5
Department of Computer Science & Engineering
y = 10
result = (x + y) * 2 > 20 # Evaluates to False (30 > 20 is True, but the
entire expression is still just an expression)

6. Function Call Expressions

Function calls can also be considered expressions because they return a value.

length = len("Hello") # Evaluates to 5, the length of the string "Hello"


Department of Computer Science & Engineering

B.Tech Third Year Fifth Semester


Subject:-Python Programming (Open Elective)
Unit IV

Conditional Statements
Conditional statements are programming constructs that execute different code paths based on
whether a condition is true or false. They are fundamental in decision-making processes within
algorithms. Here’s a brief overview:
Basic Structure
1. If Statement: Executes a block of code if the condition is true.
if condition:
# code to execute if condition is true
2. Else Statement: Executes a block of code if the condition is false.
if condition:
# code if true
else:
# code if false
3. Elif (Else If): Checks additional conditions if the previous conditions are false.
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if both conditions are false
Example in Python
age = 18

if age < 18:


print("You are a minor.")
elif age == 18:
Department of Computer Science & Engineering
print("You are exactly 18.")
else:
print("You are an adult.")
Use Cases
 Flow Control: Directing the flow of a program based on user input or other conditions.
 Validation: Checking if certain conditions are met (e.g., input validation).
 Game Logic: Making decisions based on player actions or game states.
Best Practices
 Keep it Simple: Avoid overly complex conditions for better readability.
 Indentation: Properly indent code blocks for clarity.
 Logical Operators: Use and, or, and not to combine conditions effectively.
In Python, decision statements are used to control the flow of execution based on certain
conditions. The primary decision statements in Python include if, elif, and else. Here’s a detailed
breakdown of how to define and write these statements.
Defining and writing decision statements
Defining Decision Statements
1. If Statement: Executes a block of code if the condition is true.
2. Elif Statement: Stands for "else if" and allows you to check multiple conditions.
3. Else Statement: Executes a block of code if none of the preceding conditions are true.
Syntax
The basic syntax for these statements is:
if condition:
# code to execute if condition is true
elif another_condition:
# code to execute if another_condition is true
else:
# code to execute if none of the above conditions are true
Examples
Department of Computer Science & Engineering
1. Basic Example
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You are exactly 18.")
else:
print("You are an adult.")
2. Using Multiple Conditions
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or lower")
Best Practices
 Readability: Write clear and simple conditions to improve code readability.
 Indentation: Always use consistent indentation (typically 4 spaces) to define code
blocks.
 Comments: Add comments to explain complex logic.
 Limit Nesting: Avoid deeply nested conditions; consider breaking them into functions if
they become too complex.
Loops and iteration
Loops and iteration are fundamental concepts in programming that allow you to execute a block
of code multiple times based on certain conditions. In Python, there are two primary types of
Department of Computer Science & Engineering
loops: for loops and while loops. Here’s a detailed overview of both, including their syntax, use
cases, and examples.
1. For Loops
Definition: A for loop iterates over a sequence (like a list, tuple, string, or range) and executes a
block of code for each item in that sequence.
for item in iterable:
# code to execute for each item
Example
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# Using range() to iterate a specific number of times


for i in range(5): # Iterates from 0 to 4
print(i)
2. While Loops
Definition: A while loop repeatedly executes a block of code as long as a specified condition is
true.
Syntax
while condition:
# code to execute while condition is true
Example
# Simple counter using a while loop
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter
3. Nested Loops
Department of Computer Science & Engineering
You can nest loops inside one another. This is useful for iterating over multi-dimensional data
structures like lists of lists.
Example
# Nested for loops
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num)
4. Loop Control Statements
Python provides control statements to modify the loop behavior:
 break: Exits the loop immediately.
 continue: Skips the current iteration and proceeds to the next one.
 pass: A null operation; does nothing.
Example
# Using break
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)

# Using continue
for i in range(5):
if i == 2:
continue # Skips the rest of the loop body when i is 2
print(i)
Definition of Loops
Loops: A loop is a programming structure that repeats a sequence of instructions until a specific
condition is met or until all items in a collection have been processed. They are used to automate
repetitive tasks and can help reduce code duplication.
Department of Computer Science & Engineering
Types of Loops
1. For Loop: Used to iterate over a sequence (like a list, tuple, string, or range) and execute
a block of code for each item in that sequence.
2. While Loop: Executes a block of code as long as a specified condition is true. This loop
checks the condition before each iteration.
Syntax and Usage
1. For Loop
Syntax:
for variable in iterable:
# Code to execute for each item
Example:
# Iterating over a list
animals = ["dog", "cat", "rabbit"]
for animal in animals:
print(animal)
2. While Loop
Syntax:
while condition:
# Code to execute while the condition is true
Example:
# Simple countdown using a while loop
count = 5
while count > 0:
print(count)
count -= 1 # Decrement the counter
Key Characteristics
 Iteration: Each time the loop executes, it’s called an iteration. In a for loop, each item
from the iterable is processed once. In a while loop, iterations continue as long as the
condition remains true.
Department of Computer Science & Engineering
 Termination: A loop must eventually terminate; otherwise, it will result in an infinite
loop. For for loops, this is controlled by the length of the iterable. For while loops, it
relies on the condition to eventually become false.
Loop Control Statements
 break: Exits the loop immediately.
 continue: Skips the current iteration and proceeds to the next one.
 pass: Does nothing and acts as a placeholder.
Definition of Recursion
Recursion: A method of solving a problem where the solution depends on solutions to smaller
instances of the same problem. A recursive function typically has two main components:
1. Base Case: A condition under which the function stops calling itself, preventing infinite
recursion.
2. Recursive Case: The part of the function that calls itself with a modified argument,
moving towards the base case.
How Recursion Works
1. The function checks if it meets the base case.
2. If it does, it returns a result directly.
3. If it doesn’t, it performs some operations and calls itself with a new argument.
4. This process continues until the base case is reached.
Example: Factorial
The factorial of a number nnn (denoted as n!n!n!) is the product of all positive integers up to
nnn.
Recursive Definition:
 Base Case: 0!=10! = 10!=1
 Recursive Case: n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)!
Python Implementation
def factorial(n):
# Base case
if n == 0:
Department of Computer Science & Engineering
return 1
# Recursive case
return n * factorial(n - 1)

# Test the function


print(factorial(5)) # Output: 120
Example: Fibonacci Series
The Fibonacci series is defined as follows:
 Base Cases:
o fib(0)=0fib(0) = 0fib(0)=0
o fib(1)=1fib(1) = 1fib(1)=1
 Recursive Case:
o fib(n)=fib(n−1)+fib(n−2)fib(n) = fib(n-1) + fib(n-2)fib(n)=fib(n−1)+fib(n−2)
Python Implementation
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function


print(fibonacci(6)) # Output: 8

Illustrative programs
1. Factorial Calculation (Recursion)
This program calculates the factorial of a number using recursion.
Department of Computer Science & Engineering
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
# Test the function
num = 5
print(f"The factorial of {num} is {factorial(num)}") # Output: 120
2. Fibonacci Series (Recursion)
This program generates the Fibonacci series up to a specified number of terms using recursion.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
# Test the function
terms = 6
print("Fibonacci series:")
for i in range(terms):
print(fibonacci(i), end=' ') # Output: 0 1 1 2 3 5
3. Simple Calculator (Decision Statements)
This program performs basic arithmetic operations based on user input.
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
Department of Computer Science & Engineering
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"The result is: {result}")
elif choice == '2':
result = num1 - num2
print(f"The result is: {result}")
elif choice == '3':
result = num1 * num2
print(f"The result is: {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"The result is: {result}")
else:
print("Error: Division by zero.")
else:
print("Invalid input.")
# Run the calculator
calculator()
4. Prime Number Checker (Loop and Decision Statements)
This program checks if a number is prime.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
Department of Computer Science & Engineering
return False
return True
# Test the function
number = 29
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
5. Simple Guessing Game (Loops)
This program implements a simple number guessing game.
import random
def guessing_game():
number_to_guess = random.randint(1, 100)
attempts = 0
guess = 0
print("Guess the number between 1 and 100!")
while guess != number_to_guess:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number_to_guess:
print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number in {attempts} attempts.")
# Run the guessing game
guessing_game()
Department of Computer Science & Engineering

B.Tech Third Year Fifth Semester


Subject:-Python Programming (Open Elective)
Unit V

Functions in Python

A function is a block of code designed to perform a specific task. It can take inputs, process
them, and return an output.

Defining a Function

To define a function, you use the def keyword followed by the function name and parentheses.
Here’s an example:

def add_numbers(a, b):


"""Return the sum of a and b."""
return a + b

Using a Function

You can call the function by providing the required arguments:

result = add_numbers(5, 3)
print(result) # Output: 8

Modules in Python

A module is a file that contains Python code, such as functions and variables, which can be
imported into other Python scripts. This allows you to organize your code better and reuse it
across different programs.

Creating a Module

1. Create a file named math_operations.py:

# math_operations.py

def add(a, b):


"""Return the sum of a and b."""
return a + b

def subtract(a, b):


"""Return the difference of a and b."""
return a - b
Department of Computer Science & Engineering

def multiply(a, b):


"""Return the product of a and b."""
return a * b

def divide(a, b):


"""Return the quotient of a and b."""
if b == 0:
return "Error! Division by zero."
return a / b

Using a Module

To use the functions from your module, you can import it into another Python file.

1. Create a new file named main.py:

# main.py

import math_operations

# Using the functions from the module


result_add = math_operations.add(10, 5)
result_subtract = math_operations.subtract(10, 5)
result_multiply = math_operations.multiply(10, 5)
result_divide = math_operations.divide(10, 5)

print(f"Addition: {result_add}") # Output: Addition: 15


print(f"Subtraction: {result_subtract}") # Output: Subtraction: 5
print(f"Multiplication: {result_multiply}") # Output: Multiplication: 50
print(f"Division: {result_divide}") # Output: Division: 2.0

Summary

 Functions allow you to encapsulate code for specific tasks.


 Modules help organize related functions and variables into separate files for better
maintainability and reuse.

Recursive functions

Recursive functions are functions that call themselves in order to solve a problem. They typically
break down a problem into smaller subproblems and solve each one until reaching a base case,
which stops the recursion.

Components of a Recursive Function

1. Base Case: A condition that stops the recursion.


2. Recursive Case: The part of the function that calls itself with a modified argument.
Department of Computer Science & Engineering
Example: Factorial Function

The factorial of a number nnn (denoted as n!n!n!) is the product of all positive integers up to
nnn. The recursive definition is:

 n!=n×(n−1)!n! = n \times (n - 1)!n!=n×(n−1)!


 Base case: 0!=10! = 10!=1

Defining a Recursive Function

Here’s how you can implement the factorial function recursively in Python:

def factorial(n):
"""Calculate the factorial of n using recursion."""
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

Using the Recursive Function

You can call the function and see the results:

print(factorial(5)) # Output: 120


print(factorial(0)) # Output: 1

Example: Fibonacci Sequence

Another common example of a recursive function is calculating the Fibonacci sequence, where
each number is the sum of the two preceding ones:

 F(0)=0F(0) = 0F(0)=0
 F(1)=1F(1) = 1F(1)=1
 F(n)=F(n−1)+F(n−2)F(n) = F(n - 1) + F(n - 2)F(n)=F(n−1)+F(n−2)

Defining the Fibonacci Function


def fibonacci(n):
"""Calculate the nth Fibonacci number using recursion."""
if n == 0: # Base case
return 0
elif n == 1: # Base case
return 1
else: # Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)

Using the Fibonacci Function


print(fibonacci(5)) # Output: 5
Department of Computer Science & Engineering
print(fibonacci(10)) # Output: 55

Considerations

 Efficiency: Recursive functions can be less efficient than iterative solutions, especially if they
compute the same values multiple times (as in the Fibonacci example). Techniques like
memoization can help improve performance.
 Stack Overflow: Too many recursive calls can lead to a stack overflow error. Ensure that the
base case is reached to avoid infinite recursion.

Illustrative programs

1. Factorial Calculation

This program calculates the factorial of a number using recursion.

def factorial(n):
"""Calculate the factorial of n using recursion."""
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

# Example usage
number = 5
print(f"Factorial of {number} is {factorial(number)}") # Output: 120

2. Fibonacci Sequence

This program calculates the nth Fibonacci number recursively.

def fibonacci(n):
"""Calculate the nth Fibonacci number using recursion."""
if n == 0: # Base case
return 0
elif n == 1: # Base case
return 1
else: # Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
n = 10
print(f"The {n}th Fibonacci number is {fibonacci(n)}") # Output: 55

3. Sum of a List

This program calculates the sum of all elements in a list using recursion.
Department of Computer Science & Engineering
def sum_list(lst):
"""Calculate the sum of a list using recursion."""
if not lst: # Base case: if the list is empty
return 0
else: # Recursive case
return lst[0] + sum_list(lst[1:])

# Example usage
numbers = [1, 2, 3, 4, 5]
print(f"The sum of the list is {sum_list(numbers)}") # Output: 15

4. Reverse a String

This program reverses a string using recursion.

def reverse_string(s):
"""Reverse a string using recursion."""
if len(s) == 0: # Base case: empty string
return s
else: # Recursive case
return s[-1] + reverse_string(s[:-1])

# Example usage
string = "Hello"
print(f"The reverse of '{string}' is '{reverse_string(string)}'") # Output:
olleH

You might also like