Table of contents
- 1. What is Python? and explain its datatype in Python.
- 2.Explain the operator in Python?
- Comparison Operators in Python
- Logical Operators in Python
- Bitwise Operators in Python
- 3. Write a Program to check the greatest of 4 numbers without using AND operator.
- 4.Write a program to check even no if prime or not?
- 5.Write a program to print the Fibonacci series of a given number.
- 6.Write a program to factorial no of a given number.
- 7.Explain the looping statements in Python.
- For-loop Syntax:
- Input:
- Output:
- While-loop Syntax:
- Input:
- Output:
- 8. Explain exceptional handling with examples of predefined exceptions.
- 9.Explain the OOPS concept in Python
- 10.File handling with the example of read and write mode in Python
- 11.Conditional statement in Python
1. What is Python? and explain its datatype in Python.
Python is Open source, general purpose, high-level, and object-oriented programming language.
Guido van Rossum created it
Python consists of vast libraries and various frameworks like Django, Tensorflow, Flask, Pandas, Keras, etc.
Python is also platform-independent, which means that Python code can run on different operating systems, such as Windows, macOS, and Linux. This makes it a flexible and portable language that can be used for various applications.
Data type
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, data types are actually classes and variables are instances (objects) of these classes.
Python has the following data types built-in by default: Numeric(Integer, complex, float), Sequential(string,lists, tuples), Boolean, Set, Dictionaries, etc
To check what is the data type of the variable used, we can simply write: your_variable=100
type(your_variable)
Python supports the following data types:
Numeric types:
int: represents integer values (e.g: 1, 2, 3).
float: represents floating-point numbers with decimal places (e.g: 3.14, 2.0).
complex: represents complex numbers in the form a + bi (e.g: 2+3j).
Boolean type:
- bool: represents either True or False.
Sequence types:
str: represents a sequence of characters.(e.g: "Hello World!", "Test string")
list: represents an ordered collection of elements that can be changed (mutable). (e.g: a= [1,2,3,4,5,6])
tuple: represents an ordered collection of elements that cannot be changed (immutable). (e.g: tuple = ("parrot", "sparrow"))
range: represents a sequence of numbers that can be iterated over. (e.g: range(5) returns 0, 1, 2, 3, 4)
Set types:
The set represents an unordered collection of unique elements. (e.g: myset = {"apple", "banana", "cherry"})
NoneType:
NoneType is a special data type in Python that represents the absence of a value. It is often used as a default value or a placeholder. (e.g: x = None => print(x))
Mapping type:
- dict: represents a collection of key-value pairs. (e.g: a = {1:"first name", 2: "last name", "age":33})
2.Explain the operator in Python?
Operators are used to performing operations on variables and values.
Types of Operators in Python
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power
Here is an example showing how different Arithmetic Operators in Python work:
# Examples of Arithmetic Operator
a = 9
b = 4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Modulo of both number
mod = a % b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(mod)
print(p)
13 5 36 1 65
Comparison Operators in Python
# Examples of Relational Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
False
True
False
True
False
True
Logical Operators in Python
# Examples of Logical Operator
a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
# Print not a is False
print(not a)
Output
False
True
False
Bitwise Operators in Python
# Examples of Bitwise operators
a = 10
b = 4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Output
0
14
-11
14
2
40
3. Write a Program to check the greatest of 4 numbers without using AND operator.
python program uses the built-in function max() to find the largest of 4 numbers. The max function can take any number of arguments and hence can be used to find the maximum of 3 or 5 numbers as well,
num1 = 10
num2 = 20
num3 = 30
num4 = 40
print(max(num1,num2,num3,num4)) # prints 40
4.Write a program to check even no if prime or not?
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, int(num/2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
#output
11 is a prime number
5.Write a program to print the Fibonacci series of a given number.
Fibonacci sequence:
The Fibonacci sequence specifies a series of numbers where the next number is found by adding up the two numbers just before it.
# Function for nth Fibonacci number
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
# Driver Program
print(Fibonacci(9))
#output
34
6.Write a program to factorial no of a given number.
A Factorial is a non-negative integer. It is the product of all positive integers less than or equal to that number you ask for factorial. It is denoted by an exclamation sign (!).
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
Enter a number: 10
The factorial of 10 is 3628800
7.Explain the looping statements in Python.
Sr.No. | Loop Type & Description |
1 | while loop repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. |
2 | for loop executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
3 | nested loopsYou can use one or more loops inside any another while, for, or do..while loop. |
For-loop Syntax:
for variable in sequence:
statements(s)
Input:
a = 5
for i in range(0, a):
print(i)
Output:
0
1
2
3
4
While-loop Syntax:
While condition:
statement(s)
Input:
count = 0
while (count < 5):
count = count + 1
print("Flexiple")
Output:
Flexiple
Flexiple
Flexiple
Flexiple
Flexiple
8. Explain exceptional handling with examples of predefined exceptions.
The try
block lets you test a block of code for errors.
The except
block lets you handle the error.
The else
block lets you execute code when there is no error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
#output
Something went wrong when writing to the file
Here are some commonly used predefined exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer.
NameError: This exception is raised when a variable or function name is not found in the current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
ImportError: This exception is raised when an import statement fails to find or load a module.
FileNotFoundError: Raised when a file or directory is requested, but it cannot be found.
9.Explain the OOPS concept in Python
Object-oriented programming (OOP) is a programming paradigm that treats data as objects, which are entities that have both data and methods (functions) associated with them. In Python, objects are created using the class
keyword.
Here is an example of a simple class in Python:
Python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def drive(self):
print("The car is driving")
def stop(self):
print("The car is stopping")
This class defines a car object with three attributes: make, model, and year. It also defines two methods: drive()
and stop()
.
To create an object from this class, we use the new
keyword:
Python
my_car = Car("Honda", "Civic", 2023)
This creates a new car object with the specified attributes. We can then access the object's attributes and methods using dot notation:
Python
print(my_car.make) # Prints "Honda"
my_car.drive() # Prints "The car is driving"
my_car.stop() # Prints "The car is stopping"
OOP is a powerful programming paradigm that can be used to create complex and sophisticated programs. It is a good choice for projects that require data abstraction, encapsulation, inheritance, and polymorphism.
Here are some of the benefits of using OOP in Python:
Data abstraction: OOP allows us to hide the implementation details of our objects, making our code more modular and reusable.
Encapsulation: OOP allows us to group together related data and methods, making our code easier to understand and maintain.
Inheritance: OOP allows us to reuse code by inheriting from existing classes. This can save us a lot of time and effort when developing new applications.
Polymorphism: OOP allows us to use the same interface for different types of objects. This can make our code more concise and easier to read.
10.File handling with the example of read and write mode in Python
File handling in Python allows you to interact with files on your computer. You can read data from files or write data to files using different modes. The two most common modes are read mode ('r'
) and write mode ('w'
). Let's see how you can use these modes with examples:
- Read Mode ('r'): When you open a file in read mode, you can only read the contents of the file. The file must already exist; otherwise, a
FileNotFoundError
will be raised.
Example of reading from a file:
try:
file = open('example.txt', 'r') # Open file in read mode
contents = file.read() # Read the entire contents of the file
print(contents)
file.close() # Close the file
except FileNotFoundError:
print("File not found.")
In the above example, we open the file named "example.txt" in read mode ('r'
). The read()
method is used to read the entire contents of the file, which are then printed. Finally, we close the file using the close()
method to free up system resources.
- Write Mode ('w'): When you open a file in write mode, you can write data to the file. If the file doesn't exist, a new file will be created. If the file already exists, its previous contents will be overwritten.
Example of writing to a file:
try:
file = open('example.txt', 'w') # Open file in write mode
file.write("Hello, World!") # Write data to the file
file.close() # Close the file
except:
print("An error occurred.")
In this example, we open the file "example.txt" in write mode ('w'
). We then use the write()
method to write the string "Hello, World!" to the file. If the file already existed, its previous contents would be replaced with the new data. Finally, we close the file.
Here is a breakdown of the different modes that can be used to open a file in Python:
r
- Read mode. This mode will open the file for reading. If the file does not exist, an error will be raised.w
- Write mode. This mode will open the file for writing. If the file does not exist, it will be created. If the file does exist, its contents will be overwritten.a
- Append mode. This mode will open the file for appending. If the file does not exist, it will be created. If the file does exist, new data will be appended to the end of the file.rb
- Read binary mode. This mode will open the file for reading in binary format.wb
- Write binary mode. This mode will open the file for writing in binary format.ab
- Append binary mode. This mode will open the file for appending in binary format.
11.Conditional statement in Python
A conditional statement in Python is a statement that allows you to make decisions based on the value of a variable or expression. There are three main types of conditional statements in Python:
If statement: The if statement is the most basic type of conditional statement. It allows you to execute a block of code if a condition is met.
If-else statement: The if-else statement allows you to execute one block of code if a condition is met, and another block of code if the condition is not met.
If-elif-else statement: The if-elif-else statement allows you to execute one block of code if a condition is met, another block of code if a different condition is met, and a third block of code if neither condition is met.
Here is an example of an if statement:
Python
# Check if the number is even
number = 10
if number % 2 == 0:
print("The number is even")
In this example, the if
statement checks if the value of the variable number
is even. If it is, the code inside the if
block will be executed. Otherwise, the code inside the if
block will be skipped.
Here is an example of an if-else statement:
Python
# Check if the number is even
number = 10
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
In this example, the if-else
statement checks if the value of the variable number
is even. If it is, the code inside the if
block will be executed. Otherwise, the code inside the else
block will be executed.
Here is an example of an if-elif-else statement:
Python
# Check if the number is even
number = 10
if number % 2 == 0:
print("The number is even")
elif number % 3 == 0:
print("The number is divisible by 3")
else:
print("The number is not even or divisible by 3")
In this example, the if-elif-else
statement checks if the value of the variable number
is even. If it is, the code inside the if
block will be executed. Otherwise, the code inside the elif
block will be checked. If the value of the variable number
is divisible by 3, the code inside the elif
block will be executed. Otherwise, the code inside the else
block will be executed.
12.Explain the error in Python
An error in Python is an unexpected event that occurs during the execution of a program. Errors can be caused by a variety of factors, such as:
Syntax errors: These errors occur when the code violates the syntax rules of the Python language. For example, a syntax error would occur if you forgot to close a parenthesis or quotation mark.
Runtime errors: These errors occur when the code is syntactically correct, but it does something that is impossible or unexpected. For example, a runtime error would occur if you tried to divide a number by zero.
Logic errors: These errors occur when the code is syntactically correct and it does not do anything impossible or unexpected, but it does not produce the desired results. For example, a logic error would occur if you wrote a program to calculate the area of a circle, but the program always outputs the wrong answer.
Here is an example of a syntax error in Python:
Python
print("Hello, world!")
This code will produce the following error message:
Code snippet
SyntaxError: EOL while scanning string literal
The error message is telling us that the Python interpreter found an end-of-line (EOL) character while it was scanning a string literal. This is because we forgot to close the quotation mark at the end of the string.
Here is a corrected version of the code:
Python
print("Hello, world!")
This code will not produce any errors and will print the following output:
Code snippet
Hello, world!
Here is an example of a runtime error in Python:
Python
print(1 / 0)
This code will produce the following error message:
Code snippet
ZeroDivisionError: division by zero
The error message is telling us that we tried to divide a number by zero. This is not possible in Python, so the interpreter raised an error.
Here is a corrected version of the code:
Python
print(1 / 2)
This code will not produce any errors and will print the following output:
Code snippet
0.5
Here is an example of a logic error in Python:
Python
def area_of_circle(radius):
return 3.14 * radius * radius
print(area_of_circle(5))
This code will produce the following output:
Code snippet
15.707963267948966
However, the area of a circle with a radius of 5 is actually 78.53981633974483. This is because the code is using the wrong value for pi.
Here is a corrected version of the code:
Python
def area_of_circle(radius):
return pi * radius * radius
print(area_of_circle(5))
This code will not produce any errors and will print the following output:
Code snippet
78.53981633974483
13.Explain string function in Python
In Python, strings are sequences of characters, and there are numerous built-in string functions that allow you to manipulate and work with strings. Here are some commonly used string functions in Python:
len()
: Thelen()
function returns the length (number of characters) of a string.
Example:
message = "Hello, world!"
length = len(message)
print(length) # Output: 13
lower()
andupper()
: Thelower()
function converts all characters in a string to lowercase, while theupper()
function converts them to uppercase.
Example:
message = "Hello, world!"
lower_case = message.lower()
upper_case = message.upper()
print(lower_case) # Output: hello, world!
print(upper_case) # Output: HELLO, WORLD!
strip()
: Thestrip()
function removes leading and trailing whitespace (spaces, tabs, newlines) from a string.
Example:
message = " Hello, world! "
stripped_message = message.strip()
print(stripped_message) # Output: "Hello, world!"
split()
: Thesplit()
function splits a string into a list of substrings based on a specified separator. By default, the separator is whitespace.
Example:
message = "Hello, world!"
words = message.split()
print(words) # Output: ['Hello,', 'world!']
join()
: Thejoin()
function concatenates elements of an iterable (such as a list) into a single string using a specified separator.
Example:
words = ['Hello', 'world!']
message = ' '.join(words)
print(message) # Output: "Hello world!"
replace()
: Thereplace()
function replaces all occurrences of a specified substring in a string with another substring.
Example:
message = "Hello, world!"
new_message = message.replace("world", "Python")
print(new_message) # Output: "Hello, Python!"
find()
andindex()
: Thefind()
andindex()
functions search for a substring within a string and return the index of its first occurrence. The difference is thatfind()
returns -1 if the substring is not found, whileindex()
raises aValueError
.
Example:
message = "Hello, world!"
index1 = message.find("world")
index2 = message.index("world")
print(index1) # Output: 7
print(index2) # Output: 7
Thank You