0% found this document useful (0 votes)
2 views17 pages

Practical Programs

The document provides a comprehensive guide to basic Python programming concepts, including conditional statements, loops, and data structures such as lists, tuples, sets, and dictionaries. It includes practical examples and exercises for number classification, sum calculation, factorial computation, and various operations on data structures. Additionally, it covers Python operators, comparisons, and a quiz section to reinforce learning.

Uploaded by

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

Practical Programs

The document provides a comprehensive guide to basic Python programming concepts, including conditional statements, loops, and data structures such as lists, tuples, sets, and dictionaries. It includes practical examples and exercises for number classification, sum calculation, factorial computation, and various operations on data structures. Additionally, it covers Python operators, comparisons, and a quiz section to reinforce learning.

Uploaded by

urssugi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PRACTICAL PROGRAMS

CHAPTER 1 - BASICS OF PYTHON

Ex. No 1(a) Number Classification (Conditional - if-elif-else)

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

if number > 0:

print("The number is positive.")

elif number < 0:

print("The number is negative.")

else:

print("The number is zero.")

Ex. No 1(b) Sum of Numbers (Looping - for loop)

limit = int(input("Enter a positive integer limit: "))

total_sum = 0

for i in range(1, limit + 1):

total_sum += i

print(f"The sum of numbers from 1 to {limit} is: {total_sum}")

Ex. No 1(c) Even or Odd Numbers

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

if (num % 2) == 0:

print("{0} is Even".format(num))

1
else:

print("{0} is Odd".format(num))

Ex. No 1(d) Factorial Calculation

num = int(input("Enter a non-negative integer: "))

factorial = 1

if num < 0:

print("Factorial does not exist for negative numbers.")

elif num == 0:

print("The factorial of 0 is 1.")

else:

for i in range(1, num + 1):

factorial *= i

print(f"The factorial of {num} is {factorial}.")

Ex. No 2(a) List Operation

my_list = [1, "apple", 3.14, True]

print(my_list[1])

my_list[0] = 10

print(my_list)

my_list.append("banana")

print(my_list)

for item in my_list:

print(item)

2
Ex. No 2(b) Tuple Operation

my_tuple = (1, "apple", 3.14)

print(my_tuple[1])

for item in my_tuple:

print(item)

Ex. No 2(c) Set Operation

my_set = {1, 2, 3, 2, 4}

print(my_set)

my_set.add(5)

print(my_set)

my_set.remove(2)

print(my_set)

set1 = {1, 2, 3}

set2 = {3, 4, 5}

print([Link](set2))

Ex. No 2(d) Dictionary Operation

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

print(my_dict["name"])

my_dict["age"] = 31

print(my_dict)

3
my_dict["occupation"] = "Engineer"

print(my_dict)

for key in my_dict:

print(key)

for value in my_dict.values():

print(value)

for key, value in my_dict.items():

print(f"{key}: {value}")

Python Program: Demonstration of Operators

Algorithm

1. Initialize two integer variables.

2. Perform arithmetic operations.

3. Perform relational comparisons.

4. Apply logical operators on relational results.

5. Display the results.

# Demonstration of Arithmetic, Relational and Logical Operators

a = 10

b=5

# Arithmetic Operators

print("Arithmetic Operators")

print("a + b =", a + b)

print("a - b =", a - b)

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

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

4
print("a % b =", a % b)

# Relational Operators

print("\nRelational Operators")

print("a > b =", a > b)

print("a < b =", a < b)

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

print("a != b =", a != b)

print("a >= b =", a >= b)

print("a <= b =", a <= b)

# Logical Operators

print("\nLogical Operators")

print("(a > b) and (a != b) =", (a > b) and (a != b))

print("(a < b) or (a == b) =", (a < b) or (a == b))

print("not(a == b) =", not(a == b))

OUTPUT

Arithmetic Operators

a + b = 15

a-b=5

a * b = 50

a / b = 2.0

a%b=0

Relational Operators

a > b = True

5
a < b = False

a == b = False

a != b = True

a >= b = True

a <= b = False

Logical Operators

(a > b) and (a != b) = True

(a < b) or (a == b) = False

not(a == b) = True

Python Program: Largest of Three Numbers

Algorithm

1. Read three numbers from the user.

2. Compare the numbers using if, elif, and else.

3. Display the largest number.

# Program to find the largest of three numbers

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

b = int(input("Enter second number: "))

c = int(input("Enter third number: "))

if a >= b and a >= c:

print("Largest number is:", a)

elif b >= a and b >= c:

print("Largest number is:", b)

else:

print("Largest number is:", c)

6
OUTPUT

Enter first number: 12

Enter second number: 25

Enter third number: 18

Largest number is: 25

Python Program: List Operations

Algorithm

1. Create a list with initial elements.

2. Access list elements using index positions.

3. Modify list elements using index assignment.

4. Display the updated list.

# Program to demonstrate list operations

# Creating a list

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

print("Original List:", numbers)

# Accessing elements

print("First element:", numbers[0])

print("Third element:", numbers[2])

print("Last element:", numbers[-1])

# Modifying elements

numbers[1] = 25 # Modify second element

numbers[3] = 45 # Modify fourth element

7
print("Modified List:", numbers)

OUTPUT

Original List: [10, 20, 30, 40, 50]

First element: 10

Third element: 30

Last element: 50

Modified List: [10, 25, 30, 45, 50]

Python Program: Dictionary Operations

Algorithm

1. Create a dictionary with key–value pairs.

2. Access dictionary values using keys.

3. Modify existing values.

4. Add a new key–value pair.

5. Delete a key from the dictionary.

6. Display the dictionary.

# Program to demonstrate dictionary operations

# Creating a dictionary

student = {

"roll_no": 101,

"name": "Arun",

"branch": "CSE"

print("Original Dictionary:", student)

8
# Accessing elements

print("Name:", student["name"])

print("Branch:", student["branch"])

# Modifying elements

student["branch"] = "AI & DS"

# Adding a new element

student["year"] = 3

# Deleting an element

del student["roll_no"]

print("Modified Dictionary:", student)

OUPUT

Original Dictionary: {'roll_no': 101, 'name': 'Arun', 'branch': 'CSE'}

Name: Arun

Branch: CSE

Modified Dictionary: {'name': 'Arun', 'branch': 'AI & DS', 'year': 3}

Comparison of Mutable and Immutable Datatypes in Python

Aspect Mutable Datatypes Immutable Datatypes

Objects whose values can be Objects whose values cannot be


Definition
changed after creation changed after creation

Memory New object is created when value


Same object is modified
Behavior changes

Common Types list, dict, set int, float, str, tuple

Performance Efficient for frequent updates Safer and faster for fixed data

9
Aspect Mutable Datatypes Immutable Datatypes

Hashable (can be used as dictionary


Hashable Not hashable keys)

. What is Python?

A. A low-level programming language


B. A machine-dependent language
C. A high-level, interpreted programming language
D. An assembly language
Answer: C

2. Python was developed by

A. Dennis Ritchie
B. James Gosling
C. Guido van Rossum
D. Bjarne Stroustrup

Answer: C

3. The Python Interpreter is used to

A. Compile Python programs into machine code


B. Execute Python programs line by line
C. Convert Python to C language
D. Debug hardware errors

Answer: B

4. Which of the following is a valid Python identifier?

10
A. 2variable
B. variable_1
C. variable-1
D. @variable

Answer: B

5. Python language semantics refers to

A. Syntax rules only


B. Meaning and behavior of language constructs
C. Program execution speed
D. Memory allocation

Answer: B

6. Which of the following is NOT a built-in data type in Python?

A. List
B. Tuple
C. Array
D. Dictionary

Answer: C

7. Which data type is used to store decimal values?

A. int
B. float
C. complex
D. bool

Answer: B

8. What will be the output of the expression: type(10)?

A. <class 'float'>
B. <class 'int'>

11
C. <class 'str'>
D. <class 'bool'>

Answer: B

9. Variables in Python

A. Must be declared explicitly


B. Require data type declaration
C. Are dynamically typed
D. Must start with a number

Answer: C

10. Which function is used to display output in Python?

A. display()
B. print()
C. show()
D. output()

Answer: B

11. Which function is used to read input from the user?

A. get()
B. read()
C. input()
D. scan()

Answer: C

12. Which operator is used for exponentiation in Python?

A. ^
B. *
C. **
D. //

12
Answer: C

13. Which operator performs floor division?

A. /
B. %
C. **
D. //

Answer: D

14. Which of the following is a relational operator?

A. =
B. ==
C. +=
D. //

Answer: B

15. The logical AND operator in Python is

A. &&
B. &
C. and
D. AND

Answer: C

16. Which flow control statement is used for conditional execution?

A. for
B. while
C. if
D. break

Answer: C

13
17. Which statement is used to exit a loop immediately?

A. exit
B. stop
C. break
D. continue

Answer: C

18. Which statement skips the current iteration of a loop?

A. skip
B. continue
C. pass
D. break

Answer: B

19. A List in Python is

A. Immutable
B. Ordered and mutable
C. Unordered
D. Fixed in size

Answer: B

20. Which of the following creates a list?

A. {1,2,3}
B. (1,2,3)
C. [1,2,3]
D. <1,2,3>

Answer: C

14
21. A Tuple is

A. Mutable
B. Unordered
C. Immutable and ordered
D. Dynamic

Answer: C

22. Which symbol is used to define a tuple?

A. {}
B. []
C. ()
D. <>

Answer: C

23. A Set in Python

A. Allows duplicate elements


B. Is ordered
C. Stores unique elements
D. Uses index values

Answer: C

24. Which of the following defines a set?

A. {1,2,3}
B. [1,2,3]
C. (1,2,3)
D. set(1,2,3)

Answer: A

25. A Dictionary in Python stores data in the form of

15
A. Values only
B. Index and value
C. Key–value pairs
D. Ordered lists

Answer: C

26. Which symbol is used to access dictionary values?

A. ()
B. {}
C. []
D. <>

Answer: C

27. Which of the following is true about dictionaries?

A. Duplicate keys allowed


B. Keys must be mutable
C. Keys must be unique
D. Dictionaries are ordered

Answer: C

28. Which function returns the length of a sequence?

A. count()
B. size()
C. len()
D. length()

Answer: C

29. Which of the following is a sequence data type?

A. List
B. Tuple

16
C. String
D. All of the above

Answer: D

30. Which keyword is used to define a function in Python?

A. function
B. def
C. define
D. fun

Answer: B

17

You might also like