PYTHON
PYTHON
PYTHON PROGRAMMING
CLASS: I CS
2MARKS
1.Define: Computer Software.
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?
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.
Relational operators are symbols that perform operations on data and return a
result as true or false depending on the comparison conditions.
RELATIONAL OPERATORS: ==, != , < , <= , > , >=
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
def functionName():
# What to make the function do
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:-
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)
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:
○ 'w': Write. Opens the file for writing (creates a new file if it doesn't exist).
○ 'a': Append. Opens the file for appending data.
Once the file is open, you can read its contents using several methods:
● readlines(): Reads all lines of the file into a list, where each element is a line.
print(content)
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.
4. Closing a File
It is essential to close the file after completing the operations to free up system resources.
file.close()
content = file.read()
print(content)
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)
0
1
2
3
4
1. Creation:
● 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])
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:
● 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])
python
Copy
arr = np.array([1, 2, 3, 4, 5])
mean_value = np.mean(arr) # Output: 3.0
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:
● 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
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
Python, Boolean operators are used to perform logical operations and evaluate expressions as
True or False. The primary Boolean operators are:
python
x=5
y = 10
python
x=5
y = 10
python
x=5
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).
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
python
def func():
print("Function called")
return True
2. or Operator
● Example:
python
x = 10
y=5
if x > 15 or y > 3:
python
def func():
print("Function called")
return True
3. not Operator
● Example:
python
x = 10
Resu
Expression
lt
True and
True
True
Fals
False or False
e
Fals
not True
e
Boolean operators are frequently used in if, while, and other control flow structures:
python
x=7
y=3
1. math
● Provides mathematical functions like trigonometry, logarithms, and constants like pi.
python
import math
2. os
● Helps interact with the operating system, such as reading/writing files, and managing
directories.
python
import os
3. sys
● Provides access to system-specific parameters and functions.
python
import sys
4. datetime
python
5. random
python
import random
6. json
python
import json
7. re
python
import re
pattern = r'\d+'
8. collections
● Offers specialized data structures like Counter, deque, defaultdict, etc.
python
9. itertools
● Provides tools for working with iterators, like permutations, combinations, and
infinite sequences.
python
import itertools
10. functools
python
@lru_cache(maxsize=None)
def factorial(n):
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)
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:
python
# Parent class
class Animal:
self.name = name
def speak(self):
class Dog(Animal):
def speak(self):
class Cat(Animal):
def speak(self):
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Call methods
o It defines a general structure for all animals, with an initializer and a speak()
method.
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.
1. Single Inheritance:
o A single child class inherits from one parent class (as shown in the example
above).
2. Multiple Inheritance:
python
class A:
def method_a(self):
class B:
def method_b(self):
pass
obj = C()
3. Multilevel Inheritance:
python
class A:
pass
class B(A):
pass
class C(B):
pass
4. Hierarchical Inheritance:
5. Hybrid Inheritance:
o A mix of different types of inheritance.