Python Assignment
Python Assignment
Python is a versatile and powerful programming language that is widely used for a variety of
applications, from web development to data analysis, artificial intelligence, scientific computing,
and more.
Here are the core features and advantages of Python:
1. Simple and Readable Syntax:
Python is designed to be easy to read and write, which makes it accessible to beginners and
efficient for experienced developers. Its syntax is similar to plain English, making it more intuitive
and concise.
2. Interpreted Language:
Python is an interpreted language, meaning code is executed line by line, allowing for rapid
testing and debugging. This eliminates the need for a separate compilation step, speeding up
development.
3. Dynamically Typed:
Variables can change types dynamically, which provides flexibility and reduces boilerplate code,
though it may impact runtime performance in some cases.
4. Object-Oriented and Procedural Programming Support:
Python supports both object-oriented programming (OOP) and procedural programming. This
allows developers to use OOP principles like inheritance, encapsulation, and polymorphism or
write code in a more functional or modular style.
5. Large Standard Library:
Python has an extensive standard library that provides modules and functions for various tasks
like file handling, mathematical operations, regular expressions, threading, and more, reducing
the need to install additional packages for common tasks.
6. Cross-Platform Compatibility:
Python is cross-platform and works on major operating systems like Windows, macOS, and Linux.
Python code is typically portable across these platforms with minimal changes, facilitating
development in diverse environments.
7. Support for Multiple Paradigms:
Python supports multiple programming paradigms, including procedural, functional, and object-
oriented programming. This flexibility makes it suitable for a wide range of programming tasks
and user preferences.
Advantages of Python
Easy to Learn and Use: Python's simplicity and readability make it a great language for
beginners and professionals alike.
Productivity and Speed: With its simplicity and large library support, Python allows
developers to build and deploy applications faster.
Scalability: Python can handle tasks of varying complexity, from simple scripts to complex
web applications and large data analyses.
Extensive Use in Diverse Domains: Python's versatility makes it suitable for web
development, scientific research, data analysis, artificial intelligence, automation, and more.
Active Community Support: Python has one of the largest programming communities,
making it easier to find solutions, libraries, and tutorials.
2. Explain data types available in python?
Python provides a range of built-in data types that help developers handle different types of
data in various formats. Here’s a summary of the main data types in Python:
1.Numeric Types:
Integer (int): Represents whole numbers, positive or negative, with no decimal point.
Example: x = 10 y = -5
Float (float): Represents real numbers, positive or negative, with a decimal point. Used
for floating-point calculations. Example: pi = 3.14
2. String (str): Strings are sequences of characters enclosed in single, double, or triple
quotes. Strings are immutable, meaning they can’t be modified after creation.
greeting = "Hello, World!"
multiline_text = '''This is a multi-line string.
3. Boolean: The Boolean data type has two possible values: `True` or `False`, typically used
for conditional statements.
is_active = True
has_permission = False
4.Sequence Types:
List : An ordered, mutable sequence of items that can hold items of different types.
Lists are defined using square brackets [].
Example: fruits = ["apple", "banana", "cherry"]
Tuple (tuple): An ordered, immutable sequence of items. Tuples are defined using
parentheses ().
Example: tuple = (10, 20)
Range (range): Represents an immutable sequence of numbers, often used in loops.
Created using the range() function. Example: numbers = range(5) # Generates
numbers 0 to 4
5.Mapping Type
Dictionary (dict): An unordered collection of key-value pairs. Dictionaries are mutable and
defined using curly braces `{}` with key-value pairs separated by colons.
Example: person = {"name": "Alice", "age": 30, "city": "New York"}
6. Set Types
Set (set): An unordered collection of unique elements, created using curly braces `{}` or
the `set()` function. Sets are mutable and useful for mathematical set operations.
Example: unique_numbers = {1, 2, 3, 4}
Frozen Set (frozenset): An immutable version of a set, created using the `frozenset()`
function. It has all the properties of a set but cannot be modified after creation
Example: fixed_set = frozenset([1, 2, 3, 4])
Type Conversion
Python allows conversion between data types using functions like `int()`, `float()`, `str()`,
`list()`, `tuple()`, `set()`, and `dict()`, depending on the desired target type.
3. Explain the operators present in python?
Python has a variety of operators that allow for computations, comparisons, and data
manipulations in a concise way. These operators are grouped into different types based on their
functionality. Here’s an overview of each type:
1. Arithmetic Operators: Used for basic mathematical operations.
Addition, Subtraction, multiplication, Division, Floor Division, Modulus,
Exponentiation(power).
5+2=7
5-2=3
5*2=10
5/2=2.5
5%2=1
5//2=2
5**2=25
2. Comparison Operators: Used to compare two values. These operators return a Boolean value
(`True` or `False`).
Equal to (==)Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
3. Logical Operators: Used to combine conditional statements.
and: Returns True if both conditions are true.
(5 > 3) and (3 < 5) # Result: True
or: Returns True if at least one condition is true.
(5 > 3) or (3 > 5) # Result: True
not: Returns True if the condition is false.
not(5 > 3) # Result: False
4. Assignment Operators: Used to assign values to variables. There are shorthand versions that
perform an operation and assign the result simultaneously.
=, +=, -=, *=, /=, %=, //=, **=
a=5
b+=5
c-=10
d*=2
e/=5
f%=3
g//=9
h**=3
5. Membership Operators: Used to check if a value is in a sequence like a list, tuple, or string.
in: Returns True if the specified value is in the sequence.
3 in [1, 2, 3] # Result: True
not in: Returns `True` if the specified value is not in the sequence.
4 not in [1, 2, 3] # Result: True
6. Identity Operators: Used to check if two objects are the same in memory.
is : Returns `True` if both variables point to the same object.
x = [1, 2, 3]
y=x
x is y # Result: True
is not: Returns `True` if both variables do not point to the same object.
x = [1, 2, 3]
y = [1, 2, 3]
x is not y # Result: True, as they are different objects with the same content
5. WAP to input 10 numbers and print the sum of even numbers and product of odd
numbers.?
arr=[]
for i in range(10):
num=int(input("Enter any positive number : "))
arr.append(num)
sum=0
prod=1
for j in range(10):
if arr[j]%2==0:
sum+=arr[j]
else:
prod*=arr[j]
print("Sum of even number is : ", sum)
print("Product of odd number is : ", prod)
6. WAP to input 10 numbers into list and print the average of buzz numbers.?
l=[]
for i in range(10):
num=int(input("Enter auy number : "))
l.append(num)
sum=count=0
for j in range(10):
if l[j]%10==7 or l[j]%7==0:
sum+=l[j]
count+=1
avg=sum/count
print("Average of Buzz number is : ", avg)
7. Explain any five function of list with example?
In Python, lists come with various built-in functions (methods) that make it easier to manipulate
and process list elements. Here are five commonly used list functions with examples:
1. append(): The `append()` method adds a single element to the end of a list. It modifies the
list in place and does not return a new list.
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. extend(): The `extend()` method adds each element of an iterable (like a list, tuple, or string)
to the end of the list. It’s similar to `append()` but can add multiple elements at once.
Example:
fruits = ["apple", "banana"]
more_fruits = ["orange", "grape"]
fruits.extend(more_fruits)
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']
3. insert(): The `insert()` method inserts an element at a specific position in the list. The first
argument is the index where the element will be inserted, and the second argument is the
element itself.
Example:
colors = ["red", "blue", "green"]
colors.insert(1, "yellow")
print(colors) # Output: ['red', 'yellow', 'blue', 'green']
4. remove(): The `remove()` method removes the first occurrence of a specified element from
the list. If the specified element does not exist in the list, it raises a `ValueError`.
**Example:**
animals = ["dog", "cat", "rabbit", "cat"]
animals.remove("cat")
print(animals) # Output: ['dog', 'rabbit', 'cat']
5. pop(): The `pop()` method removes and returns the element at the specified index. If no
index is provided, it removes and returns the last element of the list.
Example:
items = ["pen", "pencil", "eraser"]
removed_item = items.pop(1)
print(items) # Output: ['pen', 'eraser']
print(removed_item) # Output: 'pencil'
15.WAP to input any sentence and count the number of words using function?
def count_word():
str=input("Enter a sentence : ")
count=0
for i in range(len(str)):
if str[i]==" ":
count+=1
print(str)
print("Number of words in given Sentence is : ", count+1)
count_word()
16. WAP to write 5 lines into text file and print the number of vowels present into it?
with open("que16.txt", "w") as file:
for i in range(5):
line = input(f"Enter line {i+1}: ")
file.write(line + "\n")
vowel_count = consonant_count=0
vowels = "AEIOUaeiou"
with open("que16.txt", "r") as file:
for line in file:
for char in line:
if char in vowels:
vowel_count += 1
else:
consonant_count +=1
print(f"The total number of vowels in the file is: {vowel_count}")
print(f"The total number of vowels in the file is: {consonant_count}")
18.WAP to pass a word into function and function will return the reverse of word.?
def reverse_word(word):
return word[::-1]
input_word = input("Enter a word: ")
print("Original word : ", input_word)
reversed_word = reverse_word(input_word)
print("Reversed word : ", reversed_word)
19.WAP to input 10 numbers into tuple and print the largest and smallest number present
into it using function?
def number():
arr=[]
for i in range(10):
num=int(input("Enter a number : "))
arr.append(num)
t=tuple(arr)
max=min=0
for j in range(len(t)-1):
if t[j]>max:
max=t[j]
if t[j]<min:
min=t[j]
print(t)
print("Maximum Number is : ", max)
print("Minimum number is : ", min)
number()
20.WAP to input any number and check it is special number or not using function?
Sum of factorial of digit of a number is equal to actual number.
Ex: 145 = 1!+4!+5!
def special(num):
original_number=num
max_sum=0
while(num>0):
rem=num%10
sum=1
for i in range(1,rem+1):
sum*=i
max_sum+=sum
num//=10
if max_sum==original_number:
print(f"{original_number} is a special number.")
else:
print(f"{original_number} is not a special number.")
n=int(input("Enter a number to check it is a special number or
not : "))
special(n)