0% found this document useful (0 votes)
12 views7 pages

Python Programming Practical Exercises

The document outlines various practical exercises in Python programming, covering topics such as displaying messages, operators, conditional statements, looping, list, tuple, set, and dictionary operations, as well as functions, modules, classes, and basic usage of libraries like Pandas and Tkinter. Each practical includes code snippets and their expected outputs, along with some error messages encountered during execution. The exercises aim to provide hands-on experience with fundamental Python concepts and functionalities.

Uploaded by

Jay U. Mahankar
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)
12 views7 pages

Python Programming Practical Exercises

The document outlines various practical exercises in Python programming, covering topics such as displaying messages, operators, conditional statements, looping, list, tuple, set, and dictionary operations, as well as functions, modules, classes, and basic usage of libraries like Pandas and Tkinter. Each practical includes code snippets and their expected outputs, along with some error messages encountered during execution. The exercises aim to provide hands-on experience with fundamental Python concepts and functionalities.

Uploaded by

Jay U. Mahankar
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

Practical 1: Display Message and Read Data

print("Welcome to Python Programming!")

data = input("Enter something: ")

print("You entered:", data)

Output:

Error: raw_input was called, but this frontend does not support input requests.

Practical 2: Operators in Python

a, b = 10, 3

print("Arithmetic:", a + b)

print("Relational:", a > b)

print("Logical:", a > 5 and b < 5)

print("Bitwise:", a & b)

print("Identity:", a is b)

Output:

Arithmetic: 13

Relational: True

Logical: True

Bitwise: 2

Identity: False

Practical 3: Conditional Statements

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

if x > 0:

print("Positive")

elif x < 0:

print("Negative")

else:

print("Zero")

Output:

Error: raw_input was called, but this frontend does not support input requests.
Practical 4: Looping Statements

for i in range(5):

print(i)

i = 0

while i < 5:

print(i)

i += 1

Output:

Practical 5: Loop Control Statements

for i in range(5):

if i == 3:

continue

print(i)

if i == 4:

break

Output:

4
Practical 6: List Operations

lst = [1, 2, 3]

[Link](4)

print(lst)

[Link](2)

print(lst)

Output:

[1, 2, 3, 4]

[1, 3, 4]

Practical 7: Tuple Operations

tpl = (1, 2, 3)

print(tpl)

print(tpl[1])

Output:

(1, 2, 3)

Practical 8: Set Operations

s = {1, 2, 3}

[Link](4)

[Link](2)

print(s)

Output:

{1, 3, 4}

Practical 9: Dictionary Operations

d = {'a': 1, 'b': 2}

d['c'] = 3

[Link]('a')

print(d)

Output:
{'b': 2, 'c': 3}

Practical 10: Function with Arguments

def add(a, b=0):

return a + b

print(add(2, 3))

print(add(4))

Output:

Practical 11: Lambda, Map, Reduce

from functools import reduce

nums = [1, 2, 3, 4]

square = list(map(lambda x: x**2, nums))

print(square)

sum_all = reduce(lambda x, y: x + y, nums)

print(sum_all)

Output:

[1, 4, 9, 16]

10

Practical 12: User Defined Module

# [Link]

def square(x):

return x * x

# [Link]

import module

print([Link](5))

Output:

Error: No module named 'module'


Practical 13: Use of Modules

import math

import random

print([Link](16))

print([Link](1, 10))

Output:

4.0

Practical 14: User Defined Package

# package/[Link]

def greet():

return "Hi"

# [Link]

from package import module

print([Link]())

Output:

Error: No module named 'package'

Practical 15: Class and Objects

class Demo:

def show(self):

print("Hello")

d = Demo()

[Link]()

Output:

Hello

Practical 16: Constructors

class Test:

def __init__(self, x=0):

self.x = x
def display(self):

print(self.x)

t1 = Test()

t2 = Test(10)

[Link]()

[Link]()

Output:

10

Practical 17: Method Overloading/Overriding

class A:

def show(self): print("A")

class B(A):

def show(self): print("B")

b = B()

[Link]()

Output:

Practical 18: Inheritance

class A:

def msg(self): print("A")

class B(A): pass

b = B()

[Link]()

Output:

Practical 19: Pandas Basics

import pandas as pd

s = [Link]([1,2,3])
print(s)

df = [Link]({'A':[1,2], 'B':[3,4]})

print(df)

Output:

0 1

1 2

2 3

dtype: int64

A B

0 1 3

1 2 4

Practical 20: Tkinter Basics

import tkinter as tk

win = [Link]()

[Link]("My App")

[Link]()

Output:

Error: no display name and no $DISPLAY environment variable

Common questions

Powered by AI

Loops, as demonstrated in practicals 4 and 5, are fundamental in executing tasks that require repetitive operations, with added control using statements like 'break' and 'continue' to manage flow. However, list comprehensions, though not explicitly discussed in source 1, offer a more Pythonic way to create lists by directly iterating over sequences. They are generally more concise and potentially faster as they typically reduce the overhead of function calls. For example, iterating through a list with a comprehension [i for i in range(5)] would be more succinct compared to using a for-loop explicitly to append elements to a list .

Constructors in Python, demonstrated in practical 16, are special methods, defined with __init__, which automatically execute upon object instantiation, enabling the initialization of the object’s state. They set initial values for the object's attributes, thereby ensuring the object's consistency and readiness for use immediately after creation. For example, in practical 16, the constructor allows for objects of class 'Test' to be instantiated with varying initial states, showing their significance in controlling object initialization processes .

Each data structure in Python serves different purposes and offers various operations. Lists, as shown in practical 6, allow dynamic additions and removals, making them mutable and flexible for ordered collections. Tuples, demonstrated in practical 7, are immutable, providing fixed-size and reliable sequences. Sets (practical 8) support unique element storage with efficient operations such as add and remove, useful for membership testing, while dictionaries (practical 9) allow for key-value pair operations, ideal for associative array implementations. These distinctions impact their usage depending on whether immutability, order, or uniqueness is required .

User-friendly interfaces in GUI applications are crucial for enhancing user experience by making software intuitive and accessible, as seen with the Tkinter example in practical 20. Although the practical example did not succeed due to a missing display environment, Tkinter generally allows developers to design interfaces that facilitate straightforward interaction with the application. By ensuring elements like button placement, text entry, and visibility are optimized, users can efficiently navigate and benefit from the application without requiring extensive instruction, demonstrating the importance of thoughtful GUI design in software development .

Function default parameters significantly enhance function flexibility by allowing calls with fewer arguments than specified. In practical 10, the 'add' function's second parameter 'b' has a default value of 0, enabling the function to be called with either one or two arguments. This allows for more streamlined code and reduces the need for function overloading, as functions can be crafted to handle a variety of use cases straightforwardly. It leads to cleaner and more versatile code by allowing the programmer to provide only necessary inputs without sacrificing functionality .

The fundamental difference highlighted by the practical examples is that in a traditional Python script (Practical 1 and Practical 3), the input() function waits for user input to execute the script further and print outputs based on that input. In an interactive Python environment, such as Jupyter Notebook, the raw_input error exemplifies the limitation where the environment does not support such blocking input calls, which are typical in standard Python scripts .

Method overriding, as demonstrated by practical 17, allows a subclass to provide a specific implementation of a method already defined in its superclass, thereby facilitating polymorphism. This allows the same method call to behave differently based on the object's actual class type, enabling dynamic method resolution at runtime. This concept enhances flexibility and integration of derived classes with consistent interfaces, promoting polymorphic behavior essential for developing modular and interchangeable software components .

Classes in Python, as exemplified in practical 15, function as blueprints for creating objects, encapsulating data for objects, allowing for code reuse, and aiding in the organization of code around singular entities or concepts. Inheritance, illustrated in practical 17, allows a class to inherit attributes and methods from another class, promoting code reuse and the extension of base functionalities. Together, they support the creation of hierarchical class structures and enforce clear, maintainable, and scalable code architecture essential for large-scale software projects .

Improper use of 'import' statements can lead to significant challenges such as ImportError, as seen in practicals 12 and 14, where incorrect module or package names result in runtime errors. Such issues can stem from incorrect Python path settings, misnamed module files, or improper package directory setup. These errors illustrate the need for careful management of Python import paths and package structuring to ensure seamless module and package utilization. Understanding the underlying reasons for these errors is crucial for debugging and maintaining robust codebases .

Lambda functions serve as anonymous, concise expressions used in conjunction with higher-order functions like 'map' and 'reduce' to perform efficient data manipulation by compactly specifying operations directly within the function calls. In practical 11, 'map' applies a lambda function to square each element of the list, and 'reduce' combines the list's elements using an addition operation defined by another lambda, demonstrating their role in streamlining operations that require only simple function expressions .

You might also like