Python Programming Practical Exercises
Python Programming Practical Exercises
Output:
Error: raw_input was called, but this frontend does not support input requests.
a, b = 10, 3
print("Arithmetic:", a + b)
print("Relational:", a > b)
print("Bitwise:", a & b)
print("Identity:", a is b)
Output:
Arithmetic: 13
Relational: True
Logical: True
Bitwise: 2
Identity: False
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:
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]
tpl = (1, 2, 3)
print(tpl)
print(tpl[1])
Output:
(1, 2, 3)
s = {1, 2, 3}
[Link](4)
[Link](2)
print(s)
Output:
{1, 3, 4}
d = {'a': 1, 'b': 2}
d['c'] = 3
[Link]('a')
print(d)
Output:
{'b': 2, 'c': 3}
return a + b
print(add(2, 3))
print(add(4))
Output:
nums = [1, 2, 3, 4]
print(square)
print(sum_all)
Output:
[1, 4, 9, 16]
10
# [Link]
def square(x):
return x * x
# [Link]
import module
print([Link](5))
Output:
import math
import random
print([Link](16))
print([Link](1, 10))
Output:
4.0
# package/[Link]
def greet():
return "Hi"
# [Link]
print([Link]())
Output:
class Demo:
def show(self):
print("Hello")
d = Demo()
[Link]()
Output:
Hello
class Test:
self.x = x
def display(self):
print(self.x)
t1 = Test()
t2 = Test(10)
[Link]()
[Link]()
Output:
10
class A:
class B(A):
b = B()
[Link]()
Output:
class A:
b = B()
[Link]()
Output:
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
import tkinter as tk
win = [Link]()
[Link]("My App")
[Link]()
Output:
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 .