0% found this document useful (0 votes)
17 views15 pages

502 Bca

The document provides an overview of Python's numeric types, including operators, built-in functions, and standard library modules. It covers various looping statements, lambda functions, and their characteristics, as well as the applications of Python in fields like web development, data science, and artificial intelligence. Additionally, it discusses immutable objects in Python and the functionality of the match() function.

Uploaded by

Luv Kumar
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)
17 views15 pages

502 Bca

The document provides an overview of Python's numeric types, including operators, built-in functions, and standard library modules. It covers various looping statements, lambda functions, and their characteristics, as well as the applications of Python in fields like web development, data science, and artificial intelligence. Additionally, it discusses immutable objects in Python and the functionality of the match() function.

Uploaded by

Luv Kumar
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

502 (theory with quite code)

By Kush
1. Summarize various Operators, built-in functions and standard
library modules that deal with Python's numeric type.

Answer: - Python operators, functions, and modules make working with


numbers in Python flexible and efficient, allowing for anything from
basic calculations to advanced mathematical and statistical
operations.

1. Operators:

Arithmetic Operators:

● +(Addition): a + b
● -(Subtraction): a- b
● *(Multiplication): a * b
● /(Division): a / b (always returns a float)
● //(Floor Division): a // b (returns the largest integer ≤ the
result)
● %(Modulo): a % b(remainder of division)
● **(Exponentiation): a ** b (a raised to the power of b)

Comparison Operators: Used for comparing numeric values.

● ==, !=, <, >, <=, >=

Assignment Operators: Used to assign values with operations.

● +=,-=, *=, /=, //=, %= (modify variable by an operation and


reassign).

2. Built-in Functions: -

● Type Conversion:
A) int(): Converts a value to an integer.
B) float(): Converts a value to a floating-point number.
C) complex(): Converts a value to a complex number (e.g.,
complex(5, 3) → 5 + 3j.
● Basic Math:
A) abs(): Returns the absolute value of a number.
B) round(): Rounds a floating-point number to a specified number
of decimal places.
C) pow(): Raises a number to a specific power (pow(base, exp[,
mod])).

● Miscellaneous:
A) divmod(): Returns a tuple of quotient and remainder, e.g.,
divmod(10, 3) → (3, 1).
B) sum(): Adds up all elements in an iterable.
C) min(), max(): Find the smallest or largest number in an
iterable.

3. Standard Library Modules

● math: Provides a range of mathematical functions.


A) [Link](x): Returns the square root of x.
B) [Link](x): Returns the factorial of x.
C) [Link](a, b): Returns the greatest common divisor.
D) [Link], math.e: Constants for π and e.
E) Trigonometric functions: [Link](), [Link](), [Link]().
F) Rounding functions: [Link](), [Link]().

● random: For generating random numbers.


A) [Link](a, b):Returns a random integer between a and b.
B) [Link](sequence): Returns a random element from a
sequence.
C) [Link](a, b): Returns a random floating-point number
between a and b.

● decimal: For decimal floating-point arithmetic with high precision.


A) [Link](): Creates a decimal object.
B) [Link]().prec = n: Sets the precision to n digits.

● fractions: For rational number calculations.


A) [Link](numerator, denominator): Creates a
fraction.
B) Provides accurate fractional operations like addition,
subtraction, etc.

● statistics: For statistical calculations. A)[Link](data):


Returns the mean (average) of data. B)[Link](data):
Returns the median of data. C)[Link](data): Returns the mode
of data.
2. (a) Define various types of looping statements
in Python. (b)Write a program for ‘pyramid' of
digits as given below:

Answer: - (a) 1. Looping Statements in Python

● for loop: Used to iterate over a sequence (list, tuple, dictionary,


set, or string) or a range of numbers.

For i in range(5):
Print(i)

● while loop: Repeats as long as a condition is true.

i = 0
While I < 5:
Print(i)
i += 1

● Nested Loops: A loop inside another loop. The inner loop runs for
every iteration of the outer loop.

For i in range (3):


For j in range (3):
Print (i,j)

B) 1
1 2 1
1 2 3 2 1
1 2 1
1

Def print_pattern():
For i in range(1, 4);
print(“ ”*(3 - i), end = “d”)
For j in range (1, i*2):
If j ≤ i:
print (j, end = “”)
else:
print(i * 2 - j, end = “”)
print ()
For i in range (2, 0, -1):
print(“” * (3 - i), end= “”)
For j in range (1, i * 2):
If j ≤ i:
print(j, end = “”)
else:
print(i * 2 - j, end = “”)

Print_pattern()

3. What is the lambda function ? What are the


characteristics of a lambda function ? Give an
example.

Answer: A lambda function in Python is a small, anonymous function


defined without a name. It is created using the lambda keyword and is
often used for short, simple operations. Lambda functions can take
any number of arguments but only contain a single expression.

lambda arguments: expression

The expression is evaluated and returned when the lambda function is


called.

Characteristics of Lambda Functions:


1. Anonymous: Lambda functions do not have a name unless explicitly
assigned to a variable.
2. Single Expression: They can contain only a single expression,
which is evaluated and returned.
3. Inline Usage: Often used where a function is needed temporarily,
such as in map(), filter(), or sorted().
4. Concise: They are written in a single line, making the code more
compact.
5. No Statements: Unlike regular functions, they cannot include
statements (e.g., loops or assignments). \
6. Scope: They inherit variables from the enclosing scope, known as
lexical scoping. colle

Example of a Lambda Function

1. Basic Example:
# A lambda function to add two numbers
Add = lambda x,y: x + y
print(add(5, 3)) # Output: 8
2. Using Lambda with Built-in Functions:
map() Function: Applies a lambda function to each item in an
iterable.

Numbers = [ 1, 2, 3, 4]
Squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]

filter() Function: Filters elements based on a condition.


Numbers = [1, 2, 3, 4, 5]
Even-numbers = list(filter(lambda x:x % 2 = 0, numbers))
Print(even_numbers) # Output: [2, 4]

sorted() Function with Key:


Words = [“apple”, “banana”, “cherry”]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # Output: [‘apple’, ‘cherry’, ‘banana’]

4. State the various applications of Python.

Answer: Python is a versatile and widely-used programming language


with applications across various domains. Its simplicity, readability,
and extensive library support make it ideal for numerous tasks. Here
are the primary applications of Python:

1. Web Development
Python frameworks like Django, Flask, and FastAPI simplify the
development of scalable and secure web applications.
● Examples: A)Building websites and APIs. B)Backend development.
C)Handling databases and server-side logic.

2. Data Science and Analysis


Python is a go-to language for data scientists due to its
powerful libraries like NumPy, Pandas, and Matplotlib.
● Applications: a)Data manipulation and analysis.
b)Datavisualization. c)Statistical modeling.

3. Artificial Intelligence and Machine Learning


Python is extensively used for AI and ML due to libraries like
TensorFlow, PyTorch, Scikit-learn, and Keras.
● Applications: a) Predictive modeling. b) Natural Language
Processing (NLP). c) Image and speech recognition.
4. Automation and Scripting
Python simplifies repetitive tasks through automation scripts.
● Applications: a) File management. b) Webscraping (using
BeautifulSoup, Scrapy). c) Automating tests and workflows.

5. Game Development
With libraries like Pygame, Python can be used for prototyping
and building simple games.
● Applications: a) 2Dgamedevelopment. b) Game scripting and
logic implementation.

6. Desktop Application Development


Python's GUI libraries like Tkinter, PyQt, and Kivy make it
suitable for building cross-platform desktop applications.
● Applications: a)Productivity tools (to-do apps, calculators).
b)Multimedia applications.

7. Embedded Systems
Python is used in microcontrollers like Raspberry Pi for
developing hardware control systems.
● Applications: a)IoT(Internet of Things) devices. B)Robotics.

8. Cyber security and Ethical Hacking


Python's flexibility makes it popular in cybersecurity and
penetration testing.
● Applications: a)Writing security tools. b)Analyzing malware.
c)Network scanning (e.g., Scapy, Nmap).

9. Scientific Computing Python is widely used in scientific research


for simulations, computations, and experiments.
● Libraries: SciPy, SymPy, and Astropy.
● Applications: a) Physics and chemistry simulations. b)Numerical
analysis.

10. Mobile Application Development


Though less common, frameworks like Kivy and BeeWare allow
Python to be used in mobile app development.
● Applications: a)Prototyping mobile interfaces. b)Developing
Android and iOS apps.

11. Cloud Computing


Python plays a vital role in cloud computing due to its
compatibility with cloud platforms like AWS, Google Cloud, and Azure.
● Applications: a)Managing cloud infrastructure. b)Automating cloud
services.
12. Education - Python is beginner-friendly and is widely used to
teach programming concepts. ● Applications: ○ Teaching coding to
beginners. ○ Creating interactive learning tools.

13. DevOps - Python aids in automating deployment, monitoring, and


system administration tasks. ● Applications: ○ Writing scripts for
CI/CD pipelines. ○ Infrastructure as Code (IaC) using tools like
Ansible.

14. Financial Technology (FinTech) - Python is heavily used in


financial services for algorithmic trading, risk management, and
financial analysis. ● Applications: ○ Stock market analysis. ○
Cryptocurrency trading bots.

15. Web Scraping - Python makes it easy to extract data from websites
for analysis or application building. ● Libraries: BeautifulSoup,
Scrapy, Selenium. ● Applications: ○ Price monitoring. ○ Competitor
analysis.

16. Audio and Video Processing - Python libraries like OpenCV and
PyDub enable multimedia processing. ● Applications: ○ Video editing
and manipulation. ○ Audio analysis and conversion.

17. Testing and QA - Python tools simplify software testing and


quality assurance. ● Applications: ○ Unit testing with unittest. ○
Automated UI testing with Selenium.

18. Blockchain Development - Python is used for creating blockchain


systems and cryptocurrencies. ● Applications: ○ Building smart
contracts. ○ Cryptocurrency analysis.

5. Explain the basic functionality of the match()


function.

Answer: - The match() function in Python is part of the re module


(regular expressions). It is used to check if a pattern matches the
beginning of a given string. If the pattern is found at the start of
the string, the function returns a match object; otherwise, it
returns None.

[Link](pattern,string, flags=0)
Parameters
1. pattern: The regular expression pattern to match.
2. string: The string where the pattern will be searched.
3. flags (optional): Special flags to modify the behavior of the
pattern (e.g., [Link] for case-insensitive matching).

Description
● match() only checks for matches at the beginning of the string.
● If the pattern does not match the starting position of the string,
the function returns None.

Return Value
● If amatchis found, a match object is returned.
● If nomatch is found, None is returned.

Example 1: Matching a pattern

import re

#Match ‘Hello’ at the start of the string


Result = [Link](r‘Hello’, ‘Hello, World!’)
if result:
print(“Match found:”, [Link]()) # Output: Match found:
Hello
else:
Print(“No match”)

Example 2: No Match

import re

#Try to match ‘World’ at the beginning of the string


Result = [Link](r‘World’, ‘Hello, World!’)

If result:
Print(“Match found:”, [Link]())
else:
Print(“No match”) # Output: No match

6.(a) Which Python objects are immutable? Explain


with examples.

Answer: (a) Immutable Objects in Python


Immutable objects are those whose state (value) cannot be changed
after they are created. In Python, several built-in types are
immutable:
Immutable Python Objects:
1. Numbers: Integers (int), Floating-point numbers (float), Complex
numbers (complex), and Booleans (bool) are immutable.

Example: x = 10
X += 1 # Creates a new object instead of modifying the
print(x) existing one

# Output: 11

2. Strings: Strings are immutable, meaning any operation that


modifies a string creates a new string.

Example: s = “Hello”
S += “World” #Creates a new string
Print(s) #Output: Hello World

3. Tuples: Tuples are immutable collections of objects.

Example: t = (1, 2, 3)
# t[0] = 10 # Error: Tuples cannot be modified
Print(t) # Output: (1, 2, 3)

4. Frozen Sets: Unlike sets, which are mutable, frozen sets are
immutable.

Example: fs = frozenset([1, 2, 3]) #[Link](4) #Error: Cannot add to


a frozen set
Print(fs) # Output: frozense({1, 2, 3})

Why Use Immutable Objects?

● Thread Safety: Immutable objects can be safely shared across


threads without the risk of unintended side effects.
● Hashability: Immutable objects can be used as keys in dictionaries
and elements in sets.

7. Discuss various applications of Artificial


Intelligence.
Answer: Artificial Intelligence (AI) has transformed industries and
everyday life through its ability to mimic human intelligence and
perform tasks autonomously. Below are the various applications of AI
across different fields:

1. Healthcare

AI is revolutionizing healthcare by improving diagnostics, treatment


planning, and patient care.

● Applications:
○ Medical Imaging and Diagnosis: AI algorithms analyze medical
images (X-rays, MRIs, CT scans) to detect diseases like cancer and
fractures with high accuracy.
○ Predictive Analytics: AI predicts disease outbreaks, patient
health deterioration, and treatment outcomes.
○ Virtual Health Assistants: AI-powered chatbots provide 24/7
medical advice and appointment scheduling.
○ Drug Discovery: AI accelerates the identification of new
drugs and vaccines.
○ Robotic Surgery: Precision-guided robots assist in complex
surgical procedures.

● Example: Google's DeepMind developed an AI model to detect eye


diseases using retinal scans.

2. Education

AI enhances the learning experience by personalizing content and


automating administrative tasks.

● Applications:
○ Personalized Learning: AI analyzes students' strengths and
weaknesses to tailor learning plans.
○ Grading Automation: AI automates the evaluation of
assignments and exams.
○ Virtual Tutors: AI-powered assistants help students
understand complex topics in real time.
○ Language Learning: AI provides real-time translations and
pronunciation corrections.

● Example: Duolingo uses AI to adapt lessons based on a user’s


progress.
3. Transportation

AI drives innovation in transportation by improving efficiency,


safety, and customer experience.

● Applications:
○ Autonomous Vehicles: Self-driving cars use AI for navigation,
traffic analysis, and obstacle avoidance.
○ Traffic Management: AI systems optimize traffic flow and
reduce congestion.
○ Predictive Maintenance: AI predicts vehicle breakdowns to
prevent accidents and delays.
○ Smart Logistics: AI optimizes routes and delivery schedules
for supply chain efficiency.

● Example: Tesla’s Autopilot uses AI for autonomous driving.

4. Finance

AI is widely used in the financial sector for fraud detection,


customer service, and decision-making.

● Applications:
○ Fraud Detection: AI systems analyze transaction patterns to
identify fraudulent activities.
○ Robo-Advisors: AI offers personalized investment advice
based on financial goals.
○ Credit Scoring: AI evaluates creditworthiness using
alternative data sources.
○ Algorithmic Trading: AI executes high-frequency trades based
on market trends.

● Example: PayPal uses AI to detect and prevent fraudulent


transactions.

5. Retail and E-commerce

AI transforms the shopping experience by offering personalized


recommendations and streamlining operations.

● Applications:
○ Product Recommendations: AI analyzes customer preferences to
suggest relevant products.
○ Customer Service: AI chatbots handle inquiries, complaints,
and order tracking.
○ Inventory Management: AI predicts demand and automates
restocking.
○ Visual Search: AI allows users to search for products using
images.

● Example: Amazon's Alexa uses AI for voice shopping and smart home
integration.

6. Entertainment

AI powers the creation, distribution, and personalization of


entertainment content.

● Applications:
○ Content Recommendation: AI suggests movies, music, and shows
based on user preferences (e.g., Netflix, Spotify).
○ GameDevelopment: AI creates intelligent and adaptive
characters in video games.
○ Deepfake Technology: AI generates realistic face swaps and
voice clones.
○ Content Creation: AI generated music, art, and scripts.

● Example: OpenAI’s GPT is used to create engaging stories and game


scripts.

7. Manufacturing

AI improves efficiency and reduces costs in manufacturing by


automating processes and predicting failures.

● Applications:
○ Predictive Maintenance: AI monitors machinery to predict and
prevent breakdowns.
○ Quality Control: AI detects defects in products using
computer vision.
○ Robotics: AI-driven robots handle repetitive and hazardous
tasks.
○ Supply Chain Optimization: AI predicts demand and manages
inventory.

● Example: BMW uses AI-powered robots in its manufacturing plants.


8. Agriculture

AI enhances agricultural productivity by providing data-driven


insights and automation.

● Applications:
○ Crop Monitoring: AI-powered drones analyze crop health and
detect diseases.
○ Precision Farming: AI optimizes irrigation, fertilization,
and pest control.
○ Yield Prediction: AI forecasts crop yields based on weather
and soil data.
○ Automated Harvesting: AI-driven robots harvest crops
efficiently.

● Example: Blue River Technology’s "See & Spray" system uses AI to


target weeds and reduce pesticide use.

[Link] is Operator in Python? Explain each type of


operator with suitable examples.

Answer: In Python, operators are special symbols or keywords used to


perform operations on variables and values. They enable computations,
comparisons, logical operations, and more.

Types of Operators in Python

1. Arithmetic Operators: These are used to perform basic mathematical


operations like addition, subtraction, multiplication, etc.

2. Assignment Operators: These are used to assign values to variables


and perform operations simultaneously.

3. Comparison Operators: These compare two values and return a


boolean result (True or False).

4. Logical Operators: These are used to combine conditional


statements.

5. Bitwise Operators: These operate at the bit level on binary


numbers.
6. Identity Operators: These check whether two variables point to the
same object in memory.
7. Membership Operators: These check if a value is a member of a
sequence (like a list or string).

8. Special Operators:

● Ternary Operator: A one-line conditional expression.


Example: x = 5 if 10 > 5 else 3→x = 5

● Operator Precedence: Determines the order of operation in


expressions.
Example: 3 + 5 * 2→Multiplication is performed first, result = 13.

[Link] function in Python? Write a program


generating Fibonacci series of n numbers.

Answer: A function in Python is a block of organized, reusable code


that performs a specific task. Functions help to modularize code,
make it more readable, and avoid repetition.

Types of Functions in Python

1. Built-in Functions: Predefined functions like print(), len(), etc.


2. User-Defined Functions: Functions created by users to perform
specific tasks.

Syntax of a Function

Def function_name(parameters):
#Optional docstring explaining the function.
#Function body
Return value #Optional

Key Points

● Defining a Function: Use the def keyword.


● Calling a Function: Use its name followed by parentheses.
● Parameters: Input to the function.
● Return Value: Output of the function using the return
statement.

Example: Fibonacci Series of n Numbers


The Fibonacci series is a sequence where each number is the sum of
the two preceding ones, starting with 0 and 1.

Def fibonacci_series(n):

Generates the Fibonacci series up to n numbers.

#Starting values
A, b = 0, 1
Series = []

For_in range(n):
[Link](a) #Append the current number to the series
a, b = b, a + b #Update values for the next iteration

return series

#Input: Number of terms in the series


num_terms = int(input(“Enter the number of terms:”))

# Function call and display the result


if num_terms < 0:
print(“please enter a positive integer.”)
else:
print(“Fibonacci series:”, fibonacci_series(num_terms))

The End

You might also like