[go: up one dir, main page]

0% found this document useful (0 votes)
27 views23 pages

PYTHON

The document provides an overview of Python programming concepts, including definitions of computer software, data types, variables, control structures, and functions. It explains key programming concepts such as recursion, looping, and file handling, along with examples of syntax and usage. Additionally, it covers the NumPy library for numerical computing and Boolean operators for logical operations.

Uploaded by

maryfathimaanuja
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)
27 views23 pages

PYTHON

The document provides an overview of Python programming concepts, including definitions of computer software, data types, variables, control structures, and functions. It explains key programming concepts such as recursion, looping, and file handling, along with examples of syntax and usage. Additionally, it covers the NumPy library for numerical computing and Boolean operators for logical operations.

Uploaded by

maryfathimaanuja
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
You are on page 1/ 23

DEPARTMENT OF COMPUTER SCIENCE

PYTHON PROGRAMMING

CLASS: I CS

SUBJECT CODE: 125C1A

2MARKS
1.Define: Computer Software.

Computer software refers to a set of instructions or programs that enable a


computer to perform specific tasks. It can be categorized into two main types: system
software (such as operating systems) and application software (such as word
processors or games).

2.Write the steps for Computational Problem Solving.

The Five Step Process


• Identify the problem.
• Express the problem in terms of a mathematical model.
• Construct a computational method for solving the model.
• Implement the computational method on a computer.
• Assess the results; if there is a relatively large disparity between your solution
and the actual solution, or what you know can actually be true for the problem, then
reassess the problem and try the process again.

3. What is datatype?

Data types define the type of data that can be stored and manipulated within a program.
Common data types include:

1. Primitive Data Types: These are basic data types like integers (int), floating-point
numbers (float), characters (char), and boolean (bool).
2. Composite Data Types: These include arrays, lists, and objects, which can store
multiple values or more complex data structures.

4.What is a Variable?

A Python variable is a symbolic name that is a reference or pointer to an object.


Once an object is assigned to a variable, you can refer to the object by that name.

5.What is a Literal?
Literals in Python is defined as the raw data assigned to variables or constants
while programming. We mainly have five types of literals which includes string
literals, numeric literals, Boolean literals, literal collections and a special literal None.
6.What is meant by an infinite loop?
An Infinite Loop in Python is a continuous repetitive conditional loop that gets
executed until an external factor interferes in the execution flow, like insufficient CPU
memory, a failed feature/ error code that stopped the execution or a new feature in the
other legacy systems that needs code integration.

7.What Is a Control Structure?

A control structure (or flow of control) is a block of programming that analyses


variables and chooses a direction in which to go based on given parameters

8.What are the relational operators?

Relational operators are symbols that perform operations on data and return a
result as true or false depending on the comparison conditions.
RELATIONAL OPERATORS: ==, != , < , <= , > , >=

9.What is the use of for loop?

A for loop is used for iterating over a sequence (that is a list, a tuple, a
dictionary, a set, or a string). This is less like the for keyword in other programming
languages, and works more like an iterator method as found in other object- orientated
programming languages

10.What is a function routine?

A function is Python's version of a program routine. Some functions are designed to


return a value, while others are designed for other purposes. Defining Functions. In addition
to the built-in functions of Python, there is the capability to define new functions.

11.Write the syntax for defining Functions.

def functionName():
# What to make the function do

12.What is recursive function?

Recursion is a common mathematical and programming concept. It means that a function


calls itself. This has the benefit of meaning that you can loop through data to reach a result.

13.What is the use of Global Variable?


A global variable in Python means having a scope throughout the program, i.e., a global
variable value is accessible throughout the program unless shadowed. A global variable in
Python is often declared as the top of the program.

14.Write the difference between Formal Parameters and Actual Arguments.


Actual Parameters Formal Parameters
The Actual parameters are the The Formal Parameters are the values
variables that are transferred to determined by the function that
the function when it is accepts values when the function
requested. is declared.
In actual parameters, only the In formal parameters, the data type is
variable is mentioned, not the required.
data types.

15.Define objects.

Objects are the instances of a particular class. Every other element in Python will be
an object of some class, such as the string, dictionary, number(10,40), etc. will be an object of
some corresponding built-in class(int, str) in Python. Objects are different copies of the class
with some actual values.

5MARKS:-

1. Explain Data Types in python.


Python Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed
on a particular data. Since everything is an object in Python
programming, Python data types are classes and variables are instances
(objects) of these classes. The following are the standard or built-in data
types in Python:
● Numeric – int, float, complex
● Sequence Type – string, list, tuple
● Mapping Type – dict
● Boolean – bool
● Set Type – set, frozenset
● Binary Types – bytes, bytearray,
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric
value. A numeric value can be an integer, a floating number, or even a
complex number. These values are defined as Python int, Python
float and Python complex classes in Python.
● Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). In Python, there
is no limit to how long an integer value can be.
● Float – This value is represented by the float class. It is a real number
with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
● Complex Numbers – A complex number is represented by a complex
class. It is specified as (real part) + (imaginary part)j . For example –
2+3j
a=5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or
different Python data types. Sequences allow storing of multiple values in
an organized and efficient fashion. There are several sequence data types
of Python:
● Python String
● Python List
● Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In
Python, there is no character data type Python, a character is a string of
length one. It is represented by str class.
List Data Type
Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be
of the same type.
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False.
Boolean objects that are equal to True are truthy (true), and those equal to
False are falsy (false)

2. Write short note onText Files


In Python, text files are commonly used for storing and retrieving data. Python provides
built-in functions to handle text files effectively.

1. Opening a Text File

To work with a text file, the first step is to open it using the built-in open() function. This
function returns a file object that can be used for reading or writing to the file.

Syntax:

file_object = open('filename.txt', 'mode')

● 'filename.txt': The name of the file you want to open.

● 'mode': Specifies the file operation mode, such as:

○ 'r': Read (default). Opens the file for reading.

○ 'w': Write. Opens the file for writing (creates a new file if it doesn't exist).
○ 'a': Append. Opens the file for appending data.

○ 'r+': Read and Write.

file = open('example.txt', 'r')

2. Reading from a Text File

Once the file is open, you can read its contents using several methods:

● read(): Reads the entire content of the file.

● readline(): Reads a single line from the file.

● readlines(): Reads all lines of the file into a list, where each element is a line.

file = open('example.txt', 'r')

content = file.read() # Reads the whole file

print(content)

3. Writing to a Text File

To write data to a file, open it in 'w' (write) or 'a' (append) mode. If you open a file in write
mode ('w'), it will overwrite the existing file. If you open it in append mode ('a'), it will add
content at the end of the file.

● write(): Writes a string to the file.

● writelines(): Writes a list of strings to the file.

file = open('example.txt', 'w')

file.write("Hello, World!") # Write text to the file

file.close() # Always close the file after writing

4. Closing a File

It is essential to close the file after completing the operations to free up system resources.

file.close()

with open('example.txt', 'r') as file:

content = file.read()

print(content)

3.Explain about recursive functions


Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a
result.
Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)
OUTPUT
Recursion Example Results:
1
3
6
10
15
21

4.Write short notes on looping.

Control statements in Python are used to control the flow of execution in a program. They
allow the programmer to make decisions and repeat certain operations based on conditions.
There are three main types of control statements: conditional statements, looping statements,
and jumping statements.

1. Conditional Statements

Conditional statements are used to make decisions in a program. They allow the program to
execute certain code blocks based on whether a condition is True or False.

if Statement
The if statement checks if a condition is True. If it is, the associated block of code is
executed.

Syntax:

if condition:
# code to execute if condition is True

Example:

age = 18
if age >= 18:
print("You are an adult.")

else Statement

The else statement executes a block of code if the condition in the if statement is False.

Syntax:

if condition:
# code to execute if condition is True
else:
# code to execute if condition is False

Example:

age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")

elif Statement

The elif (short for "else if") allows you to check multiple conditions. If the first condition is
False, the program checks the elif conditions sequentially.

Syntax:

if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
else:
# code to execute if all conditions are False
Example:

age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age <= 21:
print("You are a young adult.")
else:
print("You are an adult.")

2. Looping Statements

Looping statements are used to repeat a block of code multiple times based on a condition.

for Loop

The for loop iterates over a sequence (list, string, range, etc.) and executes a block of code
for each item.

Example:

for i in range(5):
print(i)

while Loop

The while loop repeats a block of code as long as the condition is True.

Example:

count = 0
while count < 5:
print(count)
count += 1

3. Jumping Statements

Jumping statements are used to alter the flow of control in loops and functions.

break Statement

The break statement is used to terminate the loop prematurely, regardless of the loop’s
condition.

Example:

for i in range(10):
if i == 5:
break
print(i)

This will print:

0
1
2
3
4

5.Describe about Numpy

NumPy (Numerical Python) is a popular open-source library in Python used for


numerical and scientific computing. It provides support for large, multi-dimensional
arrays and matrices, along with a collection of high-level mathematical functions to
operate on these arrays.

Here’s a detailed breakdown of NumPy:

1. Creation:

There are several ways to create NumPy arrays:

● Using lists:
You can create a NumPy array from a Python list by passing the list to
np.array().

python
Copy
import numpy as np
arr = np.array([1, 2, 3, 4])

● Using functions like np.zeros(), np.ones(), or np.arange():


o np.zeros(shape): Creates an array filled with zeros.
o np.ones(shape): Creates an array filled with ones.
o np.arange(start, stop, step): Creates an array with a range of values.

python
Copy
arr_zeros = np.zeros((3, 3)) # 3x3 matrix of zeros
arr_ones = np.ones((2, 4)) # 2x4 matrix of ones
arr_range = np.arange(0, 10, 2) # Array: [0, 2, 4, 6, 8]
2. Mathematical Functions:

NumPy provides a wide array of mathematical functions to perform operations on


arrays:

● Array operations: You can perform basic arithmetic operations on arrays like
addition, subtraction, multiplication, division, etc.

python
Copy
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2 # Output: array([5, 7, 9])

● Statistical operations: Functions like np.mean(), np.median(), np.std(), and


np.var() are available for statistical analysis.

python
Copy
arr = np.array([1, 2, 3, 4, 5])
mean_value = np.mean(arr) # Output: 3.0

● Linear algebra: NumPy has functions for matrix multiplication (np.dot(),


np.matmul()), determinant (np.linalg.det()), and other linear algebra operations.

python
Copy
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2) # Matrix multiplication
3. Indexing and Slicing:

NumPy allows for advanced indexing and slicing:

● Simple indexing: You can index and slice arrays just like Python lists.

python
Copy
arr = np.array([1, 2, 3, 4, 5])
print(arr[2]) # Output: 3

● Slicing multi-dimensional arrays: You can slice arrays along specific


dimensions.

python
Copy
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr_2d[1, 2]) # Output: 6 (Element at row 1, column 2)

10MARKS QUESTION

1.Describe Boolean operators.

Python, Boolean operators are used to perform logical operations and evaluate expressions as
True or False. The primary Boolean operators are:

1. and: Returns True if both conditions are True.

python

x=5

y = 10

print(x > 3 and y < 15) # Output: True

2. or: Returns True if at least one condition is True.

python

x=5

y = 10

print(x > 7 or y < 15) # Output: True

3. not: Negates the Boolean value of the condition.

python

x=5

print(not x > 3) # Output: False

These operators are handy for combining multiple conditions in your code. Python also
evaluates them lazily, meaning it stops checking as soon as the result is determined (short-
circuiting).

BOOLEANOPERATORS IN PYTHON DETAILS

Let’s dive deeper into Boolean operators in Python! These operators allow you to perform
logical operations, evaluate conditions, and control program flow effectively.

1. and Operator

● Functionality: Returns True only if both conditions are True. Otherwise, it returns
False.
● Example:

python

x = 10

y = 20

if x > 5 and y > 15:

print("Both conditions are True")

# Output: Both conditions are True

● Behavior: If the first condition is False, it stops checking further (short-circuiting).


Example:

python

def func():

print("Function called")

return True

print(False and func()) # Output: False (func() is not executed)

2. or Operator

● Functionality: Returns True if at least one condition is True.

● Example:

python

x = 10

y=5

if x > 15 or y > 3:

print("At least one condition is True")

# Output: At least one condition is True

● Behavior: If the first condition is True, it stops checking further (short-circuiting).


Example:

python

def func():
print("Function called")

return True

print(True or func()) # Output: True (func() is not executed)

3. not Operator

● Functionality: Inverts the Boolean value of an expression.

o True becomes False, and False becomes True.

● Example:

python

x = 10

print(not x > 5) # Output: False

Truth Table for and, or, and not:

Resu
Expression
lt

True and
True
True

True and Fals


False e

False and Fals


True e

False and Fals


False e

True or True True

True or False True

False or True True

Fals
False or False
e

Fals
not True
e

not False True


Resu
Expression
lt

Use in Conditional Statements

Boolean operators are frequently used in if, while, and other control flow structures:

python

x=7

y=3

if x > 5 and not y > 5:

print("Complex condition is True")

# Output: Complex condition is True

2.Describe Built-in Modules in python.


Python comes with a rich library of built-in modules that provide pre-coded functionality to
make programming easier. These modules cover a wide range of purposes, from
mathematical calculations to file handling and more. You simply import them into your
program to use their features.

Here are some key built-in modules and their uses:

1. math

● Provides mathematical functions like trigonometry, logarithms, and constants like pi.

python

import math

print(math.sqrt(16)) # Output: 4.0

2. os

● Helps interact with the operating system, such as reading/writing files, and managing
directories.

python

import os

print(os.name) # Output: 'posix' (on Unix-like systems) or 'nt' (on Windows)

3. sys
● Provides access to system-specific parameters and functions.

python

import sys

print(sys.version) # Displays Python version

4. datetime

● Allows you to work with dates and times.

python

from datetime import datetime

print(datetime.now()) # Displays current date and time

5. random

● Used for generating random numbers and making random selections.

python

import random

print(random.randint(1, 10)) # Random number between 1 and 10

6. json

● For working with JSON (JavaScript Object Notation) data.

python

import json

data = {"name": "Alice", "age": 25}

print(json.dumps(data)) # Converts dictionary to JSON string

7. re

● Provides support for working with regular expressions.

python

import re

pattern = r'\d+'

print(re.findall(pattern, "There are 2 cats and 3 dogs")) # Output: ['2', '3']

8. collections
● Offers specialized data structures like Counter, deque, defaultdict, etc.

python

from collections import Counter

print(Counter("hello")) # Output: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

9. itertools

● Provides tools for working with iterators, like permutations, combinations, and
infinite sequences.

python

import itertools

print(list(itertools.permutations([1, 2, 3]))) # All permutations of the list

10. functools

● Includes higher-order functions like reduce and lru_cache.

python

from functools import lru_cache

@lru_cache(maxsize=None)

def factorial(n):

return n * factorial(n-1) if n else 1

3.Explain Exception handling in python.


Exception Handling in Python allows you to handle errors gracefully and ensure your
program continues to run even when unexpected issues arise. Python uses the try, except,
else, and finally blocks for this purpose.
1. Basic Syntax
Here’s the basic structure of exception handling in Python:
python
try:
# Code that might raise an exception
x = 1 / 0 # Example of raising an error (division by zero)
except ZeroDivisionError:
# Code to execute if an exception occurs
print("Division by zero is not allowed.")
else:
# Code to execute if no exception occurs
print("No errors occurred.")
finally:
# Code that always executes, whether an exception occurs or not
print("Execution complete.")
2. Catching Specific Exceptions
You can catch specific exceptions using their class name. For example:
python
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("You must enter an integer.")
except ZeroDivisionError:
print("You cannot divide by zero.")
3. Catching Multiple Exceptions
You can handle multiple exceptions in a single except block:
python
try:
number = int(input("Enter a number: "))
result = 10 / number
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
4. The else Block
The else block is executed only when no exceptions are raised in the try block:
python
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"The result is {result}.")
5. The finally Block
The finally block executes no matter what happens, making it useful for cleanup operations:
python
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Closing the file.")
if 'file' in locals():
file.close()
6. Raising Exceptions
You can raise exceptions explicitly using the raise keyword:
python
number = -1
if number < 0:
raise ValueError("Number must be non-negative.")
7. Creating Custom Exceptions
You can define your own exceptions by creating a custom class that inherits from Exception:
python
class CustomError(Exception):
pass

try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)

4. Explain Inheritance with example.

Inheritance in Python is a mechanism that allows a class (called the child class) to inherit
attributes and methods from another class (called the parent class). This promotes code
reusability and makes it easier to create related classes. Here's an example to demonstrate
inheritance:

Example: Inheritance in Python

python

# Parent class

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

return f"{self.name} makes a sound."

# Child class inheriting from the Animal class

class Dog(Animal):

def speak(self):

return f"{self.name} barks!"

# Another child class inheriting from the Animal class

class Cat(Animal):
def speak(self):

return f"{self.name} meows."

# Create instances of the child classes

dog = Dog("Buddy")

cat = Cat("Whiskers")

# Call methods

print(dog.speak()) # Output: Buddy barks!

print(cat.speak()) # Output: Whiskers meows!

Key Points in the Example:

1. Parent Class (Animal):

o It defines a general structure for all animals, with an initializer and a speak()
method.

2. Child Classes (Dog, Cat):

o These inherit from the parent class and override the speak() method to provide
their specific behaviors.

3. Polymorphism:

o The speak() method behaves differently depending on the class it belongs to.
This is an example of polymorphism.

Types of Inheritance in Python

1. Single Inheritance:

o A single child class inherits from one parent class (as shown in the example
above).

2. Multiple Inheritance:

o A child class inherits from multiple parent classes.

python

class A:
def method_a(self):

return "A method"

class B:

def method_b(self):

return "B method"

class C(A, B):

pass

obj = C()

print(obj.method_a()) # Output: A method

print(obj.method_b()) # Output: B method

3. Multilevel Inheritance:

o A child class inherits from another child class.

python

class A:

pass

class B(A):

pass

class C(B):

pass

4. Hierarchical Inheritance:

o Multiple child classes inherit from a single parent class.

5. Hybrid Inheritance:
o A mix of different types of inheritance.

You might also like