Recommended

## Python Program to check if a number is prime or not

Python Program to check if a number is prime or not
``num = int(input("Enter a number: "))flag = False# prime numbers are greater than 1if num > 1:    # check for factors    for i in range(2, num):        if (num % i) == 0:            # if factor is found, set flag to True            flag = True            # break out of loop            breakif flag:    print(num, "is not a prime number")else:    print(num, "is a prime number")``

## Write a number between 100 to 400 such that each digit of a number is an even number

Write a number between 100 to 400 such that each digit of a number is an even number, number should be in a comma separated single line.
``values = []for i in range(100, 400):    s = str(i)    if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0):        values.append(s)print(",".join(values)) ``

## Reverse a number using Python loop

Reverse a number using Python loop

``# Ask for enter the number from the use  number = int(input("Enter the integer number: "))  revs_number = 0  while (number > 0):      # Logic      remainder = number % 10      revs_number = (revs_number * 10) + remainder      number = number // 10  print("The reverse number is : ".format(revs_number))   ``

## Python Program To Remove Punctuations

Python Program To Remove Punctuations

punctuations = '''!()-[]{};:'"\,<>./?@#\$%^&*_~'''

``my_str = "Hello!!!, World"no = ""for char in my_str:    if char not in punctuations:        no = no + charprint(no) ``

## Problem Solving Using Python

Q1:

- Explain Floor division operator with an example

- Explain Percentile operator with an example

- Explain Exponent operator with an example

- Explain Equal comparison operator with an example

- Explain Not-Equal operator with an exmaple

# % symbol in Python is called the Modulo Operator.

# It returns the remainder of dividing the left hand operand by right hand operand.

# It's used to get the remainder of a division problem

# SOLUTION

``x = 7  y = 2print ('x % y =', x % y ) x = 3  y = 4print ('x % y =', x % y ) ``

Exponent operator is used to perform exponential (power) calculations by using operators

``a = 10b = 4print ('Exponent operator:', a ** b )``

Equal operator is used to compare the two values to provide result whether they are equal or not.

If both the values are equal, we get the result as True, if not False

# SOLUTION

``x = 15y = 34print('Equal operator:',x==y)``

Not equal operator is used to compare two operands

It returns True statement if they are Not equal, and False if they are Equal

# SOLUTION

``x = 20y = 25  print('Not equal operator:', x!=y)``

Q2:  (a) I have two numbers as x = 123 and y = "465"; when I try to add these two numbers, the program fails. Debug and solve the problem.

x, y = 123, '456';

print(x+y)

``x, y = 123, '456'print(x + int(y))``

(b) We have a variable as shown below:

course = "Python fundamentals"

we would like to replace the "Python fundamentals" with the "Python for absolute beginners"

Expected output:

- course = "Python for absolute beginners"

SOLUTION b

``course = 'Python fundamentals'course = course.replace('fundamentals', 'for absolute beginners')print('course = ', course)``

(c) Imagine price of a house is 25 L. If the buyer has good credit, they need to make 10% down payment, alternately down payment is 30%. Write a program to display the rules and display the down payment.

SOLUTION c

``price = 2500000has_good_credit = Trueif has_good_credit:    down_payment = 0.1 * priceelse:    down_payment = 0.3 * price    print('Down payment: Rs.', down_payment)``

Q3: (a) Create a Vehicle class with model_name, max_speed and mileage instance attributes.

expected output:

- Model Name: Eicher

- Max speed: 100

- Mileage: 20

``class Vehicle:    def __init__(self, model_name, max_speed, capacity):        self.model_name = model_name        self.max_speed = max_speed        self.capacity = capacity                car = Vehicle("Eicher", 100, 50)print("Model Name:", car.model_name)print("Max speed:", car.max_speed)print("Capacity:", car.capacity)       ``

(b) Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare.

``class Vehicle:    def __init__(self, model_name, max_speed, capacity):        self.model_name = model_name        self.max_speed = max_speed        self.capacity = capacityclass Bus(Vehicle):    def fare(self):        default_fare = self.capacity * 100         total_fare = default_fare + (0.1 * default_fare)        return total_fareAlliance_Bus = Bus("Eicher", 12, 50)print("Total Bus fare is:", Alliance_Bus.fare())``

Q4: 1. Write a Program to create a class by name Students, and initialize attributes like name, dateofbirth, and grade while creating an object.

2. Write a Program to create an empty valid class by name Students, with no properties

3. Write a program, to create a child class 'Undergraduate' that will inherit the properties of Parent class Students and also will have it's own unique attribute(satscore)

4. Finally call each attribute to print the output

SOLUTION 1

``class Students():    def __init__(self, name, DateOfBirth, contactNumber, address):        self.name = name        self.DateOfBirth = DateOfBirth        self.number = contactNumber        self.address = address# create objectstudentA = Students('Mathew', '22-Jun-2022', '123456789', 'Anekal')``

SOLUTION 2

``class Students:    pass# create objectstudentsA = Students()``

SOLUTION 3

``class Students():    def __init__(self, name, DateOfBirth, contactNumber, address):        self.name = name        self.DateOfBirth = DateOfBirth        self.number = contactNumber        self.address = address# INHERITANCEclass Undergraduate(Students):    def __init__(self, name, DateOfBirth, number, address, SatScore):        Students.__init__(self, name, DateOfBirth, number, address)        self.SatScore = SatScore        x = Undergraduate("Mona", "22-Jun-2022", "123456789", "Anekal", "1234")SOLUTION 4print(type(x))print("Student Name: ", x.name)print("Student Birth Date: ", x.DateOfBirth)print("Student Phone Number: ", x.number)print("Student's Address: ", x.address)print("Student's SAT Score: ", x.SatScore)``

Q5: Remove duplicates from a list and create a tuple and find the minimum and maximum number

Given:

myList = [87, 45, 41, 65, 94, 41, 99, 94]

Expected Outcome:

- unique items [87, 45, 41, 65, 99]

- tuple (87, 45, 41, 65, 99)

- min: 41

- max: 99

# SOLUTION

``myList = [87, 52, 44, 53, 54, 87, 52, 53]print("Original list", myList)myList = list(set(myList))print("unique list", myList)t = tuple(myList)print("tuple ", t)print("Minimum number is: ", min(t))print("Maximum number is: ", max(t))``

Q6:

Write a program

- to remove the item present at index 4

- add the removed number to the 2nd position

- add the removed number at the end of the list.

Given:

aList = [34, 54, 67, 89, 11, 43, 94]

Expected Output:

- List After removing number at index 4:  [34, 54, 67, 89, 43, 94]

- List after adding number at index 2:  [34, 54, 11, 67, 89, 43, 94]

- List after adding number at last:  [34, 54, 11, 67, 89, 43, 94, 11]

SOLUTION

``aList = [34, 54, 67, 89, 11, 43, 94]print('aList =', aList)x = aList.pop(4)print("List After removing number at index 4: ", aList)aList.insert(2, x)print("List after adding number at index 2: ", aList)aList.append(x)print("List after adding number at last:", aList)``

Q7: (a) Using exception handling (try & finally)

- open a text file, read the contents

- finally close the file

sample text = 'Hello, I am proud to be with Alliance University!'

``try:    f = open("sample.txt", 'r')    print (f.read())finally:    f.close()``

(b)

- reopen the same file to append the text to "Hello, I am learning file operations in Python!"

- read the file again

- finally close the file to release memory

``try:    f = open("sample.txt", "w")    f.write ("Hello, I am learning file operations in Python!")     f = open("sample.txt", 'r')    print (f.read())finally:    f.close()``

Q8: (a) we have the following variables with relevant infomation

- info = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]}

how can we convert this to pandas dataframe?

# SOLUTION a

``import pandasinfo = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]}x = pandas.DataFrame(info)x``

(b)

- create an Excel file with above ID and Deapartment headers

- convert the Excel to csv file

- read the same file using pandas read function.

## Matrix Representation of Graphs

In this post, you will learn how to represent a graph in matrix form. By using this concept we can easily create implementation of adjacency matrix.

If there is an edge between two vertices then we will represent it with 1 and if there is no edge then with 0.

## Adjacency Matrix Representation of Graphs

For Undirected Graph:

 1 2 3 4 5 1 0 1 0 0 1 2 1 0 1 0 0 3 0 1 0 1 0 4 0 0 1 0 1 5 1 0 0 1 0

Directed Graphs:

 1 2 3 4 5 1 0 0 0 0 1 2 1 0 0 0 0 3 0 1 0 0 0 4 0 0 1 0 0 5 0 0 0 1 0

## Input And Output In Python

In C language we use scanf and printf for input and output but what about in python? Let's us find out in this post, So hello guys I hope you are doing well, let's discuss about it.

## Input Function In Python

``Syntax: variable_name = input('text to be displayed')``

Code

``name = input("Enter your name: ")``

Output

``````Enter your name: Praveen
``````

Input Function For Numbers

To take number as a input you can use int or float outside the paranthesis.

``name = int(input("Enter your age: "))``

Output

``````Enter your age: 21
``````

## Print Function In Python

Unlike in java where you have to type system.out.println, python has made this built-in function name very simple. Just type print() and inside bracket put the variable, constant or string.

``````print("Hello World")
``````

Output

``````Hello World
``````

## Variables In Python

A variable is the name of the location in the memory. It has three attributes:

1. Name

3. Value

## How To Use Variable In Python

Variable name = value

Unlike C where you have to declare data type, you don't need to specify the data type of variable in python. This is called as dynamically typed language. You can use the same variable for different data types.

Also you can't just declare a variable in python you need to initialize some value.

## Multiple Assignments of Variable

``````a, b, c = 1, 2, 3
print(a,b,c)
``````

We will look in detail about print and input function in next post.

Input And Output In Python

## Tokens In Python

A token is the smallest individual unit in a python program. Python have following tokens

• 1. Keywords - These are reserved words which have special meaning for the interpreter.
• 2. Identifiers - These are the names given to the different parts of the program.
• 3. Literals - These are tokens which have fixed value.
• 4. Operators - These are symbols which when put between two operands performs some operation.
• 5. Punctuators - These are symbols used to organize statements, or structures in a program.

## Keywords

In Python 3.0.7, there are 33 keywords.

 False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield

## Identifiers

Some rules you need to keep in mind while creating Identifiers.

• The first character should be letter, or +underscore. No numbers should be the first letter.
• It should not be a keyword.
• Identifers are case-sensitve.
• Except _underscore no symbol is allowed.

Some valid Identifers are:

Hello _Crackexams99

Some invalid Identifers are:

8Hello True

## Literals

There are different types of literals:

• String literals - Letters enclosed in quotes ''/"" are called string literals.
• Numeric literals - There are generally three types which are int, float, and complex.
• Boolean literals - It is True or False.
• None - It indicates nothing.

## Operators

There are different types of operators:

• Unary Operators - Requires only one operand.
• Binary Operators - Requires two operand.

• -Arithmetic Operators

OperatorFunctionSyntax
+Add two operands or unary plusx + y
-Subtract right operand from the left or unary minusx - y
*Multiply two operandsx * y
/Divide left operand by the right one (always results into float)x / y
%Modulus - remainder of the division of left operand by the rightx % y
//Floor division - division that results into whole number adjusted to the left in the number linex // y
**Exponent - left operand raised to the power of rightx**y

-Bitwise Operators

OperatorMeaningSyntax
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx >> 2
<<Bitwise left shiftx << 2

-Membership Operators

OperatorFunctionSyntax
inTrue if value/variable is found in the sequence5 in x
not inTrue if value/variable is not found in the sequence5 not in x

-Identity Operators

OperatorFunctionSyntax
isTrue if the operands are identicalx is True
is notTrue if the operands are not identicalx is not True

-Logical Operators

OperatorFunctionSyntax
andTrue if both the operands are truex and y
orTrue if either of the operands is truex or y
notTrue if operand is falsenot x

-Relational Operators

OperatorFunctionSyntax
>Greater thanx > y
<Less thanx < y
==Equal tox == y
!=Not equal tox != y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

-Assignment Operators

OperatorUseSyntax
=x = 1x = 1
+=x += 1x = x + 1
-=x -= 1x = x - 1
*=x *= 1x = x * 1
/=x /= 1x = x / 1
%=x %= 1x = x % 1
//=x //= 1x = x // 1
**=x **= 1x = x ** 1
&=x &= 1x = x & 1
|=x |= 1x = x | 1
^=x ^= 1x = x ^ 1
>>=x >>= 1x = x >> 1
<<=x <<= 1x = x << 1

## Punctuators

These are symbols used to organize statements, or structures in a program. Examples are ' " \ # @ , : = ( ) [ ] { }