0% found this document useful (0 votes)
7 views16 pages

Unit 1-1

Python 2

Uploaded by

Ajay Kanna
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)
7 views16 pages

Unit 1-1

Python 2

Uploaded by

Ajay Kanna
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/ 16

S11BLH22 PYTHON PROGRAMMING

UNIT 1 INTRODUCTION

Introduction, History, Features of Python, Data types, Variables, Expressions,


Conditional Statements, Operators, Looping, Control Statements

Practice Programs
1. Develop a python program to find the best of two test average marks out of three test’s
marks
accepted from the user and compute the overall pass percentage for their placements.
2. Write a class Money with attributes Rupees and Paise. Overload operators +=, -=, and
>= so
that they may be used on two objects. Also write functions so that a desired amount of
money
can be either added or subtracted from Money.

History of python:

Python was created by Guido van Rossum, a Dutch programmer, and its development began in
the late 1980s.

1. Origin (Late 1980s):


Guido van Rossum started working on Python in December 1989 at the Centrum Wiskunde &
Informatica (CWI) in the Netherlands.

2. Python 0.9.0 (February 1991):


The first official Python release, version 0.9.0, was released. It included features like
exception handling, functions, and modules.

3. Python 1.0 (January 1994):


Python 1.0 was a significant milestone, featuring a module system and support for functional
programming constructs.

4. Python 2.0 (October 2000):


Introduced list comprehensions, garbage collection, and Unicode support, among other
improvements.

5. Python 3.0 (December 2008):


A major release that aimed to clean up the language, removing redundancy and improving
consistency. It introduced backward-incompatible changes, leading to a division between
Python 2 and Python 3.
6. Python Software Foundation (2001):
The Python Software Foundation (PSF) was established as a non-profit organization to
promote, protect, and advance Python.

7. Python 2 Sunset (January 1, 2020):


Python 2 officially reached its end of life, with developers encouraged to migrate to Python 3
for ongoing support and updates.

8. Python 3.x (Ongoing):


Python 3 continues to receive updates and improvements. The community has largely
transitioned to Python 3, and new projects are encouraged to use this version.

Throughout its history, Python has gained popularity for its simplicity, readability, and versatility.
Its community-driven development and strong emphasis on code readability have contributed to
its widespread adoption in various fields, including web development, data science, artificial
intelligence, and more.

Features of python:

Python is a versatile programming language known for its simplicity and readability. Some key
features of Python include:

1. Readability:
Python emphasizes clean and readable code, making it easier to write and maintain.

2. Simplicity:
The language's syntax is simple and easy to learn, which accelerates development.

3. Versatility:
Python supports both procedural and object-oriented programming paradigms, making it
versatile for various applications.

4. Interpreted Language:
Python is an interpreted language, allowing for quick development and testing.

5. Dynamic Typing:
Python uses dynamic typing, enabling flexibility in variable assignment.

6. Large Standard Library:


Python includes a comprehensive standard library with modules for various tasks, reducing
the need for external libraries.

7. Community Support:
A large and active community contributes to the language's development and provides
extensive support.

8. Cross-Platform:
Python is compatible with major operating systems, allowing code portability across platforms.

9. High-Level Language:
Python abstracts low-level details, facilitating a focus on problem-solving rather than intricate
system details.

10. Open Source:


Python is open-source, fostering collaboration and continuous improvement through
community contributions.

11. Integration Capabilities:


Python easily integrates with other languages and tools, enhancing its usability in various
scenarios.

12. Web Development Frameworks:


Python has popular web frameworks like Django and Flask, simplifying web application
development.

These features contribute to Python's popularity and widespread use in diverse fields, including
web development, data science, machine learning, and more.

Data types in python:

Python has several built-in data types, including:

1. Numeric Types:
int (integer)
float (floating-point)

2. Sequence Types:
str (string)
list
tuple

3. Set Types:
set

4. Mapping Type:
dict (dictionary)
5. Boolean Type:
bool (boolean)

6. None Type:
None (represents the absence of a value or a null value)

These data types provide a versatile foundation for creating and manipulating data in Python.

Variables in python:

In Python, variables are used to store and manage data. Here are key points about variables in
Python:

1. Variable Assignment:
Variables are created by assigning a value to a name using the `=` operator.

x=5

2. Dynamic Typing:
Python is dynamically typed, meaning you don't need to explicitly declare a variable's type.
The interpreter infers the type based on the assigned value.

name = "John"
age = 25

3. Variable Naming Rules:


Variable names can include letters, numbers, and underscores but should start with a letter or
an underscore.
Python is case-sensitive, so `name` and `Name` would be different variables.

4. Reassignment:
You can reassign a variable to a new value.

x = 10
x = "hello"

5. Multiple Assignments:
Python allows multiple assignments in a single line.
a, b, c = 1, 2, 3

6. Variable Types:
Variables can hold different types of data, such as integers, floats, strings, lists, etc.

count = 10
price = 5.99
message = "Hello, Python!"

7. Constants:
While Python doesn't have constants in the traditional sense, it's a convention to use
uppercase names for variables that should not be changed.

PI = 3.14159

8. Deleting Variables:
You can delete a variable using the `del` statement.

x=5
del x

Understanding and using variables effectively is fundamental to writing Python code. They
provide a way to store and manipulate data, making your programs more flexible and dynamic.

Expressions in python:

In Python, expressions are combinations of values, variables, and operators that are evaluated
to produce a result. Here are some examples of Python expressions:

1. Arithmetic Expressions:
- Basic arithmetic operations like addition, subtraction, multiplication, and division.

result = 5 + 3 * 2 / 4

2. Relational Expressions:
Used to compare values, resulting in a Boolean value (`True` or `False`).

greater_than = 10 > 5
3. Logical Expressions:
Combine Boolean values using logical operators (`and`, `or`, `not`).

is_valid = (x > 0) and (y < 100)

4. Bitwise Expressions:
Perform bitwise operations on integers.

bitwise_result = 0b1010 & 0b1100 # Bitwise AND

5. Conditional Expressions (Ternary Operator):


A concise way to express conditional statements.

status = "valid" if is_valid else "invalid"

6. Membership Expressions:
Check if a value is a member of a sequence (e.g., a list or a string).

contains_item = "apple" in ["apple", "orange", "banana"]

7. Identity Expressions:
Check if two objects reference the same memory location.

is_same_object = obj1 is obj2

8. Function Calls:
Invoking functions is also an expression.

length = len("hello")

9. List Comprehensions:
Generate lists using a concise expression.

squares = [x**2 for x in range(5)]

10. Lambda Expressions:


Create anonymous functions using the `lambda` keyword.

add = lambda x, y: x + y

Expressions are a fundamental part of Python programming, allowing you to perform


calculations, make decisions, and manipulate data in a concise and expressive manner.

Conditional Statements in python:

Conditional statements in Python allow you to control the flow of your program based on certain
conditions. The main conditional statements are:

1. if Statement:
Executes a block of code if a specified condition is `True`.

x = 10
if x > 5:
print("x is greater than 5")

2. if-else Statement:
- Executes one block of code if the condition is `True` and another block if it's `False`.

x=3
if x % 2 == 0:
print("x is even")
else:
print("x is odd")

3. if-elif-else Statement:
Allows you to check multiple conditions in sequence.

score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
4. Nested if Statements:
You can have if statements inside other if statements.

x = 10
if x > 0:
if x % 2 == 0:
print("Positive and even")
else:
print("Positive and odd")
else:
print("Non-positive")

5. Ternary Operator:
A concise way to express a conditional statement.

result = "Even" if x % 2 == 0 else "Odd"

These conditional statements help you create more dynamic and responsive programs by
allowing your code to make decisions based on different conditions.

Operators in python:

Python supports a variety of operators that allow you to perform operations on variables and
values. Here are some of the key types of operators in Python:

1. Arithmetic Operators:
`+` (addition)
`-` (subtraction)
`*` (multiplication)
`/` (division)
`%` (modulo - remainder of division)
`**` (exponentiation)
`//` (floor division - result is rounded down to the nearest whole number)

2. Comparison (Relational) Operators:


`==` (equal to)
`!=` (not equal to)
`<` (less than)
`>` (greater than)
`<=` (less than or equal to)
`>=` (greater than or equal to)
3. Logical Operators:
`and` (logical AND)
`or` (logical OR)
`not` (logical NOT)

4. Bitwise Operators:
`&` (bitwise AND)
`|` (bitwise OR)
`^` (bitwise XOR)
`~` (bitwise NOT)
`<<` (left shift)
`>>` (right shift)

5. Assignment Operators:
`=` (assignment)
`+=` (addition assignment)
`-=` (subtraction assignment)
`*=` (multiplication assignment)
`/=` (division assignment)
`%=` (modulo assignment)
`**=` (exponentiation assignment)
`//=` (floor division assignment)

6. Identity Operators:
`is` (True if both variables point to the same object)
`is not` (True if both variables do not point to the same object)

7. Membership Operators:
`in` (True if a value is found in the sequence)
`not in` (True if a value is not found in the sequence)

8. Ternary Operator:
`x if condition else y` (returns x if the condition is True, else y)

These operators provide the building blocks for various operations in Python, allowing you to
perform calculations, make decisions, and manipulate data in your programs.

Looping in python:

Python provides several ways to implement loops, allowing you to execute a block of code
repeatedly. The main types of loops are:

1. For Loop:
Used for iterating over a sequence (such as a list, tuple, or string) or other iterable objects.

for item in iterable:


# code to execute for each item

Example:

fruits = ["apple", "banana", "orange"]


for fruit in fruits:
print(fruit)

2. While Loop:
Repeats a block of code as long as a specified condition is `True`.

while condition:
# code to execute while the condition is True

Example:

count = 0
while count < 5:
print(count)
count += 1

3. Nested Loops:
You can use loops inside other loops (nested loops) to create more complex iterations.

for i in range(3):
for j in range(2):
print(i, j)

4. Loop Control Statements:


`break`: Exits the loop prematurely.
`continue`: Skips the rest of the code inside the loop for the current iteration and moves to the
next one.

Example:

for i in range(5):
if i == 2:
continue
print(i)
if i == 3:
break

5. Range Function:
Often used with for loops to generate a sequence of numbers.

for i in range(5):
print(i)

6. Enumerate Function:
Used to iterate over both the values and their indices.

fruits = ["apple", "banana", "orange"]


for index, fruit in enumerate(fruits):
print(index, fruit)

Loops are essential for automating repetitive tasks and iterating over data structures in Python.
They provide a powerful mechanism for handling various scenarios efficiently.

Control Statements in python:

In Python, control statements are used to control the flow of a program. The main control
statements include:

1. Conditional Statements:
if Statement:

if condition:
# code to execute if the condition is True

if-else Statement:

if condition:
# code to execute if the condition is True
else:
# code to execute if the condition is False
if-elif-else Statement:

if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
else:
# code to execute if none of the conditions are True

2. Looping Statements:
For Loop:

for variable in iterable:


# code to execute for each iteration

While Loop:

while condition:
# code to execute while the condition is True

Loop Control Statements:


`break`: Exits the loop prematurely.
`continue`: Skips the rest of the code inside the loop for the current iteration and moves to
the next one.

for i in range(5):
if i == 2:
continue
print(i)
if i == 3:
break

3. Pass Statement:
Acts as a placeholder where syntactically some code is required but no action is desired or
necessary.

if condition:
pass # do nothing, just a placeholder
else:
# code to execute if the condition is False

4. Exception Handling:
try-except Statement:

try:
# code that may raise an exception
except ExceptionType as e:
# code to handle the exception

finally Statement:

try:
# code that may raise an exception
except ExceptionType as e:
# code to handle the exception
finally:
# code to execute regardless of whether an exception was raised or not

These control statements provide the necessary tools to make decisions, iterate over data, and
handle exceptions, contributing to the flexibility and functionality of Python programs.

Exercise programs:

1.simple Python program that takes three test marks for two students, calculates their average,
finds the best average, and computes the overall pass percentage for placements:

def calculate_average(marks):
return sum(marks) / len(marks)

def main():
# Input for student 1
print("Enter the marks for Student 1:")
student1_test1 = float(input("Test 1: "))
student1_test2 = float(input("Test 2: "))
student1_test3 = float(input("Test 3: "))

# Input for student 2


print("\nEnter the marks for Student 2:")
student2_test1 = float(input("Test 1: "))
student2_test2 = float(input("Test 2: "))
student2_test3 = float(input("Test 3: "))

# Calculate averages
student1_average = calculate_average([student1_test1, student1_test2, student1_test3])
student2_average = calculate_average([student2_test1, student2_test2, student2_test3])

# Find the best average


best_average = max(student1_average, student2_average)

print("\nResults:")
print(f"Student 1 Average: {student1_average:.2f}")
print(f"Student 2 Average: {student2_average:.2f}")

print(f"\nThe best average is: {best_average:.2f}")

# Overall pass percentage calculation


pass_percentage = (student1_average + student2_average) / 2
print(f"\nOverall Pass Percentage: {pass_percentage:.2f}%")

if __name__ == "__main__":
main()

This program prompts the user to enter test marks for two students, calculates the average
marks for each student, finds the best average, and computes the overall pass percentage
based on the average marks of both students.

2.Below is an example of a Money class in Python that includes attributes for Rupees
and Paise, overloads the +=, -=, and >= operators, and provides a display method:

class Money:
def __init__(self, rupees=0, paise=0):
self.rupees = rupees
self.paise = paise

def display(self):
print(f"{self.rupees} Rupees and {self.paise} Paise")

def __iadd__(self, other):


if isinstance(other, Money):
total_paise = self.rupees * 100 + self.paise + other.rupees * 100 + other.paise
self.rupees, self.paise = divmod(total_paise, 100)
return self
else:
raise ValueError("Unsupported operand type")

def __isub__(self, other):


if isinstance(other, Money):
total_paise = self.rupees * 100 + self.paise - (other.rupees * 100 + other.paise)
if total_paise >= 0:
self.rupees, self.paise = divmod(total_paise, 100)
return self
else:
raise ValueError("Subtraction result should not be negative.")
else:
raise ValueError("Unsupported operand type")

def __ge__(self, other):

You might also like