ashishksaxena.files.wordpress.com · web viewlab reports consist of one lab worksheet for each...
TRANSCRIPT
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
PPS LAB Objectives:1. Understand the basic concept of Python Programming, and its different modules that
include conditional and looping expressions, Arrays, Strings, Functions, and Structures.2. Acquire knowledge about the basic concept of writing a program. Role of constants,
variables, identifiers, operators, type conversion and other building blocks of Python Language.
3. Use of conditional expressions and looping statements to solve problems associated with conditions and repetitions. Role of Functions involving the idea of modularity. Programming using Python tool in Linux.
Purpose of the Labs:
We believe that people learn some things best by doing them. The labs for PPS provide time to do computer science under the direction of an instructor who will be serving as a facilitator during the lab session. This means that the instructor will not solve your problems or show you how to complete the activities. The instructor may provide helpful hints, ask additional questions, ask you to explain a solution, ask how you obtained a solution, or facilitate discussions about observations, experiments, results, discoveries, and other topics that arise.
Some lab activities will ask you to develop solutions to problems, program solutions in Alice or Python, and test the programs. Other activities will involve using programs we give you to illustrate important concepts in Computer Science. You will be required to make observations, form and test hypotheses, and use the results of your testing to change aspects of your programs.
The lab session format will provide opportunities for discussing your observations,
experiments, discoveries, and solutions to problems. Discussions may take place with
your lab partner, your instructor, or other lab groups. The lab materials you hand in
to your instructor will provide the opportunity to communicate in writing about the
computer science being done.
Goals we will make progress towards: Understanding that computer science is a way of thinking or asking questions
rather than just a set of facts about technology. Formulating, analyzing, and solving problems using the concept of an algorithm.
This includes the ability to solve problems with a sense of imagination and creativity.
Page 1
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Communicating effectively in both oral and written form. Understanding what computer science is, what its connections are to other subjects,
and what are some of its important questions. Having fun !!!
Student responsibilities:
You are responsible for preparing for the labs (reading the materials in the first portion of each lab), attending the lab sessions, completing the lab assignments (which may require time outside of the lab sessions), and handing in required materials on time. In particular:
Lab reports consist of one Lab Worksheet for each team of two students. All information and
answers requested during the lab will be filled in on the Worksheet; additional responses and
program printouts must be attached to the back of the lab, in the order requested. All lab
team members are responsible for the lab, and the grade earned by the lab will be assigned to
all team members.
LAB PREPARATION:
The remainder of this lab manual contains some helpful information on the software and
hardware systems you will be using this semester. This lab manual should be at your side
whenever you are logged in and doing work for this course, either in a lab or for a homework
assignment or for any other reason.
Software Tool Installation:
Python is pre-installed on most Unix systems, including Linux and MAC OS
X. But for in Windows Operating Systems , user can download from the
https://www.python.org/downloads/
from the above link download latest version of python IDE and install, recent version is
3.4.1 but mostly we can see pre-installed version 2.7.7 only.
The Python Ecosystem
The Python programming environment has
two broad subject areas:
• The language itself
• The extension packages
We can further subdivide the extension packages
into:
• The standard library of packages
Page 2
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
• The Python ecosystem of yet more extension packages,
Fig. Python Ecosystem
Anaconda Installation:
Follow following steps carefully,
• Step 1 — Retrieve the Latest Version of
Anaconda
https://www.anaconda.com/distribution/
• Step 2 — Download the Anaconda
$cd /tmp
$curl -O https://repo.anaconda.com/archive/Anaconda3-2019.03-Linux-x86_64.sh
• Step 3 — Verify the Data Integrity of the Installer
$sha256sum Anaconda3-2019.03-Linux-x86_64.sh
• Step 4 — Run the Anaconda Script
$bash Anaconda3-2019.03-Linux-x86_64.sh
Page 3
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
You’ll receive the some output to review the license agreement by pressing ENTER until you
reach the end.
• Step 5 — Activate Installation
$conda list
• Step 6 — Set Up Anaconda Environments
$conda create --name my_env python=3
• Step7 - Activate the new environment like so:
$conda activate my_env
• Step8 - Launch Anaconda
$anaconda-navigator
Page 4
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO. 01
Title:
To calculate salary of an employee given his basic pay (take as input from user). Calculate salary of employee. Let HRA be 10 % of basic pay and TA be 5% of basic pay. Let employee pay professional tax as 2% of total salary. Calculate salary payable after deductions.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To Calculate salary payable of employee
Outcomes:1. Students will be able to demonstrate calculations of employee salary.2. Students will be able to demonstrate different Operator & formulas.3. Students will be able to demonstrate different Operations on Available data of employee
salary.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
Python Basics:
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace.
What is Basic salary?
Basic salary is the base income of an individual. It is a fixed part of one's compensation package.
A basic salary depends on the employee’s designation and also the industry in which the employee works.
Basic salary is the amount paid to an employee before any extras are added or taken off, such as reductions because of salary sacrifice schemes or an increase due to overtime or a bonus. Allowances, such as internet for home-based workers or contributions to phone usage, would also be added to the basic salary.
Page 5
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Gross salary:
Gross salary is the amount calculated by adding up one's basic salary and allowances, before deduction of taxes and other deductions. It includes bonuses, over-time pay, holiday pay, and other differentials.
Gross Salary = Basic Salary + HRA + Other Allowances
Allowances:An allowance is an amount received by the employee for meeting service requirements. Allowances are provided in addition to the basic salary and vary from company to company. Some common types of allowances are shown below:
HRA or House Rent Allowance: It is an amount paid out to employees by companies for expenses related to rented accommodation.
Leave Travel Allowance (LTA): LTA is the amount provided by the company to cover domestic travel expenses of an employee. It does not include the expenses for food, accommodation, etc. during the travel.
Conveyance Allowance: This allowance is provided to employees to meet travel expenses from residence to work.
Dearness Allowance: DA is a living allowance paid to employees to tackle the effects of inflation. It is applicable to government employees, public sector employees, and pensioners only.
Other such allowances are the special allowance, medical allowance, incentives, etc.
HRA:HRA received is not fully exempt from tax. HRA that you can claim is the lowest of the following:
The total amount received as the HRA from the employer in the financial year. Actual rent paid in the year – 10% of the basic salary in the year. 50% of the annual basic salary if staying in a metro city or 40% of the annual basic
salary if staying in a non-metro city.
Sample Example:
Python program to get employee wages and number of days worked from user and find Basic
Pay, DA, HRA, PF and Net Pay.
(Note HRA, DA and PF are 10%,5%and 12% of basic pay respectively.)
Sample Input 1:
300
30
Sample Output 1: Basic Pay:3000
Page 6
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
DA: 150 HRA:300 PF:360Net Pay: 3090
Solution:
days=float(input("Enter No Days Present:"))
wages=float(input("Enter wages per Day:"))
basic=wages*days;
HRA=basic*0.1;
DA=basic*0.05;
PF=basic*0.12;
netsalary=basic+HRA+DA-
PF;
print("\nBasic:%lf \nHRA:%lf \nDA:%lf \nPF:%lf \nNet Salary:%lf" %
(basic,HRA,DA,PF,netsalary));
Calculate Gross Salary Python Program
This python program is using if else statement to compute the gross salary from basic salary input. Here we have two different logics to compute gross salary. so we are using if and else statements. # function computes the gross salary from basic salary.
Conclusion:
Thus, we have successfully understood concept of salary calculation formulas and performed
salary calculation in python.
Page 7
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.02
Title:
To accept N numbers from user. Compute and display maximum in list, minimum in list, sum and average of numbers.
Objective:
Understand basic concepts of python programming language and try to solve list concepts related programs.
Problem Statement:
To Find maximum and minimum number, sum,average from given list.
Outcomes:
1. Students will be able to understand basic concept of list in python.
2. Students will be able to demonstrate different Operator & formulas on given list.
3. Students will be able to demonstrate different types of list examples easily.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda, Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
What is list?
Python offers a range of compound datatypes often referred to as sequences. List is one of the
most frequently used and very versatile datatype used in Python.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
Page 8
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Syntax:
# empty
list my_list
= []
# list of integers
my_list = [1, 2,
3]
# list with mixed
datatypes my_list = [1,
"Hello", 3.4]
Also, a list can even have another list as an item. This is called nested
list. # nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements from a list?There are various ways in which we can access the elements of a list.
List IndexWe can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested
indexing. my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0]
) # Output: o
print(my_list[2]
) # Output: e
print(my_list[4]
)
# Error! Only integer can be used for
indexing # my_list[4.0]
Page 9
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
# Nested List
n_list = ["Happy",
[2,0,1,5]] # Nested
indexing
# Output: a
print(n_list[0]
[1])
# Output: 5print(n_list[1][3])
Fig: List Indexing
In this experiment, we will learn how to find the maximum and minimum number in a python
list. Python list can hold items of any data types. All items are separated by a comma and
placed inside a square bracket. We can access any item by using its index. The index starts at
0. The index for the first element is 0, the index of the second element is 1 etc.
Here will show you how to find the maximum and minimum number in a list using a loop. All
the numbers will be entered by the user. The user will enter the list items one by one and our
program will read them.
First, we will ask the user to enter the total number count. Then using a for loop, we will read
each number and append them to the list. Finally, again using one more for loop, we will
calculate the maximum and minimum number and print out the result. Let’s take a look into
the following sample program first.
Explanation :
1. Create one empty list my_list. We are using one empty square bracket to create the empty
Page 10
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
list. This is a list without any items.
2. Get the total number of elements the user is going to enter and save it in the count variable. This is required because we will ask the user to enter each number one by one. If the value of count is 4, the user will have to enter four numbers to add to the list.
3. Using a for loop, get the numbers and append it to the list my_list. For appending a number append method is used. This method takes the value we are adding as the parameter. For reading the value, we are using the input method. This method will read the value from the user. The return value of this method is of string type. Wrapping it as int() will convert the entered value to an integer.
4. Print the list to the user.
5. Create two variables to hold the minimum and maximum number. We are assigning the first element of the list to both of these variables first. We will update these variables on the next step. On this step, we are assuming that the minimum and maximum value of the list is equal to the first element of the list. We will compare this value with all other elements of the list one by one and update them if required.
6. Run one for loop on the list again. For each number, check if it is less than the minimum number. If yes, assign the minimum value holding variable to this number. Similarly, update the maximum value if the number is more than the current maximum.
7. After the list is completed reading, print out both maximum and minimum numbers.
Algorithm:
1.Create an empty list
named l 2.Read the value of
n
3.Read the elements of the list until
n 4.Assign l[0] as maxno
5.If l[i]>maxno then set
maxno=l[i] 6.Increment i by 1
7.Repeat steps 5-6 until i<n
8.Print the value of maximum number
Conclusion: Thus, we have studied and performed operation on list in python.
Page 11
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO. 03
Title:
To accept student’s five courses marks and compute his/her result. Student is passing if he/she
scores marks equal to and above 40 in each course. If student scores aggregate greater than
75%, then the grade is distinction. If aggregate is 60>= and <75 then the grade if first division.
If aggregate is 50>= and <60, then the grade is second division. If aggregate is 40>= and <50,
then the grade is third division
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To calculate percentage,aggregate of given five subjects in python.
Outcomes:
1. Students will be able to understand basic concept of percentage calculation in python.
2. Students will be able to demonstrate different Operator & formulas for grade and sum.
3. Students will be able to demonstrate different Operations by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda, Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
In this assignment user has to enter five different marks for five subjects. Next, it will find the
Total, average, and Percentage of those Five Subjects. For this, we are using the arithmetic
operator to perform arithmetic operations.
Problem Description
The program takes in the marks of 5 subjects and displays the grade.
Problem Solution
1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
Page 12
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.
Following flowchart will show basic idea about sum,average calculation in python , same
logic we can apply fow percentage calculation.
Fig: Flowchart for underating average, sum calculation.
Conclusion: Thus, we have performed how to calculate percentage and grade, average in python.
Page 13
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.04
Title:
To check whether input number is Armstrong number or not. An Armstrong number is an
integer with three digits such that the sum of the cubes of its digits is equal to the number itself.
Ex. 371.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To proove that given number is armstrong number in python.
Outcomes:
1. Students will be able to understand basic concept of Armstrong number logic.
2. Students will be able to demonstrate different integer number for identifying armstrong number.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
To understand this example, you should have the knowledge of following python programming
concept with basic topics:
Python if...else Statement
Python while Loop
What are if...else statement in Python?
Decision making is required when we want to execute a code only if a certain condition is
satisfied. The if…elif…else statement is used in Python for decision making.
Page 14
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Python if Statement Syntax
if test
expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Python if Statement Flowchart
Example: Python if Statement
# If the number is positive, we print an appropriate
message num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num >
0:
print(num, "is a positive number.")
print("This is also always printed.")
Page 15
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
A positive integer is called an Armstrong number of order
n if abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the
number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
Approach :
1. Read an input number using input() or raw_input().
2. Check whether the value entered is an integer or not.
3. Check input_num is greater than 0.
4. Initialize a variable named arm_num to 0.
5. Find remainder of the input number by using the mod (%) operator to get each
digit in the number.
6. Now cube each digit and add it to arm_num.
7. Floor Divide the number by 10.
8. Repeat steps 5. 6. 7 until the input_num is not greater than 0.
9. If input_num is equal to arm_num, print number is ARMSTRONG.
10. When input_num is not equals to arm_num, the number is NOT an
Armstrong number.
Conclusion:
Thus, we have studied and performed armstrong number concept in python successfully.
Page 16
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.05
Title:
To accept the number and Compute a) square root of number, b) Square of number, c) Cube
of number d) check for prime, d) factorial of number e) prime factors
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform number different operation on given number in python.
Outcomes:
1. Students will be able to understand basic concept of number operations logic.
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
To understand this experiment, you should have the knowledge of following Python
programming topics:
Python Input, Output and Import
Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations respectively. Let us see the output section first.
Python Output Using print() function
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given below. print('This sentence is output to the screen')
Page 17
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
# Output: This sentence is output to the screena = 5
print('The value of a is', a)
# Output: The value of a is 5
Python Data Types
Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
Python NumbersIntegers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class.
a = 5
print(a, "is of type",
type(a)) a = 2.0
print(a, "is of type",
type(a)) a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
For example:
>>> 2+35
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of
the operation.
Python math function | sqrt()
sqrt() function is an inbuilt function in Python programming language that returns the square root of any number.
Syntax:
math.sqrt(x)
Parameter:
Page 18
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
x is any number such that x>=0
Returns:It returns the square root of the number passed in the parameter.Example:
# Python3 program to demonstrate
the # sqrt() method
# import the math
module import math
# print the square root of 0
print(math.sqrt(0))
# print the square root
of 4 print(math.sqrt(4))
# print the square root of
3.5 print(math.sqrt(3.5))
Square of a Number
In this article, we will show you, How to write a Python Program to Calculate Square of a Number using Arithmetic Operators, and Functions with example.
allows the user to enter any numerical value. Next, it will finds the square of that number using Arithmetic Operator.
Example:
# Python Program to Calculate Square of a Number number = float(input(" Please Enter any numeric Value : ")) square = number * numberprint("The Square of a Given Number {0} = {1}".format(number, square))
Cube of a Number
we will show you, How to write a Python Program to Calculate Cube of a Number using Arithmetic Operators, and Functions with example.
Example:
# Python Program to Calculate Cube of a Number
number = float(input(" Please Enter any numeric Value : ")) cube = number * number * numberprint("The Cube of a Given Number {0} = {1}".format(number, cube))
Page 19
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Prime Number:
A positive integer greater than 1 which has no other factors except 1 and the number itself is
called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors.
But 6 is not prime (it is composite) since, 2 x 3 = 6.
Given a positive integer N. The task is to write a Python program to check if the number is prime or not.
Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.
Examples :
nput: n = 11 Output: true
Input: n = 15 Output: false
Input: n = 1 Output: false
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.
Below is the Python program to check if a number is prime:
# Python program to check if # given number is 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, num//2):
# If num is divisible by any number between # 2 and n / 2, it is not primeif (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")
Page 20
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Factorial Number:
The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
factorial() in Python
Not many people know, but python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial.
Naive method to compute factorial
Conclusion: Thus , in this experiment we have studied and performed mathematical operation on given number.
Page 21
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.06
Title:
To input binary number from user and convert it into decimal number.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform number conversion in python.
Outcomes:
1. Students will be able to understand basic concept of number conversion.
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
The number systems refer to the number of symbols or characters used to represent any
numerical value. The number system that you typically use every day is called decimal. In the
decimal system, you use ten different symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. With these ten
symbols, you can represent any quantity. Binary, hexadecimal, and octal refer to different
number systems.
When you run out of symbols, you go to the next digit placement. In the decimal system, to
represent one higher than 9, you use 10 meaning one unit of ten and zero units of one.
However, it is different in other number systems. For example, when you consider a binary
system which only uses two symbols: 0 and 1, when you run out of symbols, you need to go to
the next digit placement. So this is how you will count in binary: 0, 1, 10, 11, 100, 101 and so
on.
Let's check out some of the number systems in more detail in the next sections.
Page 22
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Convert to Binary Number
Binary integers are the number represented with base two. Which means in the binary number System, there are only two symbols used to represent numbers: 0 and 1. When you count up from zero in binary, you run out of symbols more quickly: 0, 1, ???
Furthermore, there are no more symbols left. You do not go to the digit 2 because 2 doesn't
exist in binary. Instead, you use a special combination of 1s and 0s. In a binary system, 1000 is
equal to 8 in decimal. In binary, you use powers of two, which means 8 is basically: (1(2^3)) +
(0(2^2)) + (0(2^1)) + (0(2^0))= 8. The position of the 1 and 0 defines the power to which 2 is to
be raised to.
Let's see this with a more complex example to make it clear:
Binary Number = 1001111
Decimal value = (1*(2^6)) + (0*(2^5)) + (0*(2^4)) + (1*(2^3)) + (1*(2^2)) + (1*(2^1)) + (1*(2^0))
= 79
In Python, you can simply use the bin() function to convert from a decimal value to its
corresponding binary value.
And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
Convert Binary to Decimal in Python
To convert binary to decimal number in python, you have to ask from user to enter a number in binary number system to convert that number into decimal number system as shown in the program given here.
Approach:
The idea is to extract the digits of given binary number starting from right most digit and
keep a variable dec_value. At the time of extracting digits from the binary number, multiply
the digit with the proper base (Power of 2) and add it to the variable dec_value. At the end,
the variable dec_value will store the required decimal number.
Page 23
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
For Example:
If the binary number is 111.
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
Conclusion: Thus in this experiment we have studied and performed number conversion in
python successfully.
Page 24
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.07
Title:
To accept a number from user and print digits of number in a reverse order.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform number in reverse order as per user input in python.
Outcomes:
1. Students will be able to understand basic concept of number reverse order logic.
2. Students will be able to demonstrate different integer number for identifying number operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
In this assignment we are going to perform program to reverse a number in python allows the
user to enter any positive integer and then, that number is assigned to variable Number.
Next, Condition in the While loop will make sure that, the given number is greater
than 0 From the above example, User Entered value: Number = 1456 and Reverse = 0
First Iteration
Reminder = Number
%10 Reminder =
1456%10 = 6
Reverse = Reverse *10 +
Reminder Reverse = 0 * 10 + 6 =
0 + 6 = 6 Number = Number //10
Page 25
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Number = 1456 //10 = 145
Second Iteration
From the first Iteration the values of both Number and Reverse has been changed as: Number = 145 and Reverse = 6
Reminder = Number %
10 Reminder = 145 % 10
= 5
Reverse = Reverse *10+ Reminder = 6 * 10 +
5 Reverse = 60 + 5 = 65
Number = Number //10 = 145
//10 Number = 14
Third Iteration
From the Second Iteration of Python reverse a Number program, the values of both Number and Reverse has been changed as: Number = 14 and Reverse = 65
Reminder = Number
%10 Reminder =
14%10 = 4
Reverse = Reverse *10+ Reminder = 65 * 10 +
4 Reverse = 650 + 4 = 654
Number = Number //10 = 14//10
Number = 1
Fourth Iteration
From the Second Iteration the values of both Number and Reverse has been changed as: Number = 1 and Reverse = 654
Reminder = Number
%10 Reminder = 1 %10
= 1
Reverse = Reverse *10+ Reminder = 654 * 10 +
1 Reverse = 6540 + 1 = 6541
Page 26
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Number = Number //10 = 1//10
Number = 0
Here, For the next iteration Number = 0 so, the while loop condition will fail
Problem Solution
1. Take the value of the integer and store in a variable.2. Using a while loop, get each digit of the number and store the reversed number in another variable.3. Print the reverse of the number.4. Exit.
Program/Source
Code
Here is the source code of the Python Program to reverse a given number.
n=int(input("Enter number: "))
rev=0 while(n>0):
dig=n%10 rev=rev*10+dig n=n//10
print("Reverse of the number:",rev)
Program Explanation
1. User must first enter the value and store it in a variable n.2. The while loop is used and the last digit of the number is obtained by using the modulus
operator.3. The last digit is then stored at the one’s place, second last at the ten’s place and so on.4. The last digit is then removed by truly dividing the number with 10.5. This loop terminates when the value of the number is 0.6. The reverse of the number is then printed.
Runtime Test CasesCase 1:
Enter number: 124Reverse of the number: 421
Case 2:Enter number: 4538Reverse of the number: 8354
Page 27
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Python Program to Reverse a Number Using Functions
This program to reverse a number in python allows the user to enter any positive integer
and then, we are going to reverse a number using Python Functions
Conclusion: Thus in this experiment we have studied and performed reverse number
conversion in python successfully.
Page 28
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.08
Title:
To accept list of N integers and partition list into two sub lists even and odd numbers.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform odd and even from two different list in python.
Outcomes:
1. Students will be able to understand basic concept of even odd logic.
2. Students will be able to demonstrate list operations.
3. Students will be able to demonstrate different Operations on any integer by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
•Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python. We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class.
>>>a = 5
print(a, "is of type", type(a))
>>>a = 2.0
print(a, "is of type", type(a))
Page 29
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
>>>a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].
Lists are great to use when you want to work with many related values. They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once.
When thinking about Python lists and other data structures that are types of collections, it is useful to consider all the different collections you have on your computer: your assortment of files, your song playlists, your browser bookmarks, your emails, the collection of videos you can access on a streaming service, and more.
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].
>>> a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of itemsfrom
a list. Index starts form 0 in Python.
Example
a = [5,10,15,20,25,30,35,40]
# a[2] = ?
print("a[2] = ",
a[2]) # a[0:3] = ?
print("a[0:3] = ",
a[0:3]) # a[5:] =
print("a[5:] = ", a[5:])
Page 30
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Given a list of numbers, write a Python program to count Even and Odd numbers in a List.
Example:
Input: list1 = [2, 7, 5, 64, 14] Output: Even = 3, odd = 2
Input: list2 = [12, 14, 95, 3] Output: Even = 2, odd = 2
Example 1: count Even and Odd numbers from given list using for loop
Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase even count else increase odd count.
Problem Solution
1. Take in the number of elements and store it in a variable.2. Take in the elements of the list one by one.3. Use a for loop to traverse through the elements of the list and an if statement to check if the element is even or odd.4. If the element is even, append it to a separate list and if it is odd, append it to a different one.5. Display the elements in both the lists.6. Exit.
Program Explanation
1. User must enter the number of elements and store it in a variable.2. User must then enter the elements of the list one by one using a for loop and store it in a list.3. Another for loop is used to traverse through the elements of the list.4. The if statement checks if the element is even or odd and appends them to separate lists.5. Both the lists are printed.
Runtime Test Cases
Case 1:Enter number of elements:5Enter element:67 Enter element:43 Enter element:44 Enter element:22 Enter element:455 The even list [44, 22]The odd list [67, 43, 455]
Page 31
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Case 2:Enter number of elements:3 Enter element:23Enter element:44Enter element:99 The even list [44] The odd list [23, 99]
Conclusion:Thus, in this experiment we have studied and performed operations on list successfully.
Page 32
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.09
Title:
Write a python program that accepts a string from user and perform following string
operations- i. Calculate length of string ii. String reversal iii. Equality check of two strings iii.
Check palindrome
ii. Check substring
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform String operation in python.
Outcomes:
1. Students will be able to understand basic concept of string in python.
2. Students will be able to demonstrate different operations on string.
3. Students will be able to demonstrate different Operations on any string by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:A string is a list of characters in order. A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. Strings can have spaces: "hello world". An empty string is a string that has 0 characters.
A string is a list of characters in order.A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash.
Strings can have spaces: "hello world".
An empty string is a string that has 0
characters. Python strings are immutable
Page 33
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Python recognize as strings everything that is delimited by quotation marks (" " or ' ').
String Manipulation
To manipulate strings, we can use some of Pythons built-in
methods. word = "Hello World"
>>> print word Hello World
Accessing
Use [ ] to access characters in a
string word = "Hello World"
letter=word[0]
>>> print letter H
Length
word = "Hello World"
>>> len(word) 11
Finding
word = "Hello World"
>>> print word.count('l') # count how many times l is in the string 3
>>> print word.find("H") # find the word H in the string 0
>>> print word.index("World") # find the letters World in the string 6
Count
s = "Count, the number of spaces"
>>> print s.count(' ') 8
Page 34
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Slicing
Use [ # : # ] to get set of letter
Keep in mind that python, as many other languages, starts to count from 0!!
word = "Hello World"
print word[0] #get one char of the wordprint word[0:1] #get one char of the word (same as above) print word[0:3] #get the first three charprint word[:3] #get the first three char print word[-3:] #get the last three charprint word[3:] #get all but the three first char print word[:-3] #get all but the three last character
word = "Hello World"
word[start:end] # items start through end-1 word[start:] # items start through the rest of the listword[:end] # items from the beginning through end-1 word[:] # a copy of the whole list
Split Strings
word = "Hello World"
>>> word.split(' ') # Split on whitespace ['Hello', 'World']
Startswith / Endswith
word = "hello world"
>>> word.startswith("H") True
>>> word.endswith("d") True
>>> word.endswith("w") FalseChanging Upper and Lower Case Strings
Page 35
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
string = "Hello World"
>>> print string.upper()
HELLO WORLD
>>> print string.lower() hello world
>>> print string.title() Hello World
>>> print string.capitalize() Hello world
>>> print string.swapcase() hELLO wORLD
Reverse words in a given string
Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”
Input: hello
Output:
olleh
The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contains curly braces {} as placeholders or replacement fields which gets replaced.
We can use positional arguments or keyword arguments to specify the order.
The format() method can have optional format specifications. They are separated from
field name using colon. For example, we can left-justify <, right-justify > or center ^ a string
in the given space. We can also format integers as binary, hexadecimal etc. and floats can be
rounded or displayed in the exponent format. There are a ton of formatting you can use.
Conclusion:Thus, in this experiment we have studied and performed string operation successfully.
Page 36
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
ASSIGNMENT. NO.10
Title:
To copy contents of one file to other. While copying a) all full stops are to be replaced with commas
b) lower case are to be replaced with upper case c) upper case are to be replaced with lower case.
Objective:
Understand basic concepts of programming language and try to solve mathematical calculations in programming approach with the help of formulas and equations.
Problem Statement:
To perform file handling operations in python.
Outcomes:
1. Students will be able to understand basic concept of file handling in python.
2. Students will be able to demonstrate file operations.
3. Students will be able to demonstrate different Operations on any igiven file by using own logic.
Hardware Requirement: Any CPU with i3 Processor or similar, 1 GB RAM or more,2 GB Hard Disk or more
Software Requirements: 32/64 bit Linux(Ubuntu/Fedora)Operating System, latest any Python Tool Like Anaconda,Pycharm, Python IDLE, Python Atom, Eclipse.
Theory:
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
What is a file?
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Page 37
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
Hence, in Python, a file operation takes place in the following order.
1. Open a file2. Read or write (perform operation)3. Close the file
File Handling
The key function for working with files in Python is the open()
function. The open() function takes two parameters; filename, and
mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g.
images) Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
How to open a file?
Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
Page 38
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
How to close a file Using Python?
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')# perform file operationsf.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try: f = open("test.txt",encoding = 'utf-8') # perform file operationsfinally: f.close()
How to write to File Using Python?
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n")
his program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish different lines.
How to read files in Python?
To read a file in Python, we must open the file in reading mode.
Page 39
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
There are various methods available for this purpose. We can use the read(size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
Page 40
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4
data 'This'
>>> f.read(4) # read the next 4
data ' is '
>>> f.read() # read in the rest till end of
file 'my first file\nThis file\ncontains three
lines\n'
>>> f.read() # further reading returns empty
sting ' '
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes).
>>> f.tell() # get the current file
position 56
>>> f.seek(0) # bring file cursor to initial
position 0
>>> print(f.read()) # read the entire
file This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
... print(line, end = '')
...This is my first
file This file
Page 41
D. Y. Patil College of Engineering, Akurdi Programming and problem solving Lab(2019 Pattern)
contains three lines
The lines in file itself has a newline character '\n'.
Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.
>>> f.readline()
'This is my first file\n'
>>>
f.readline()
'This file\n'
>>> f.readline()
'contains three lines\
n'
>>>
f.readline() ' '
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
Conclusion:
Thus, in this experiment we have studied file handling in python successfully.
Page 42