D. Y. Patil College of Engineering, Akurdi Programming and ...



PPS LAB Objectives:Understand the basic concept of Python Programming, and its different modules that include conditional and looping expressions, Arrays, Strings, Functions, and Structures.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.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 municating 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 the above link download latest version of python IDE and install, recent version is3.4.1 but mostly we can see pre-installed version 2.7.7 only.The Python EcosystemThe Python programming environment has two broad subject areas:The language itselfThe extension packagesWe can further subdivide the extension packages into:The standard library of packagesThe Python ecosystem of yet more extension packages,761363135254Fig. Python EcosystemAnaconda Installation:Follow following steps carefully,Step 1 — Retrieve the Latest Version of Anaconda 2 — Download the Anaconda$cd /tmp$curl -O 3 — Verify the Data Integrity of the Installer$sha256sum Anaconda3-2019.03-Linux-x86_64.shStep 4 — Run the Anaconda Script$bash Anaconda3-2019.03-Linux-x86_64.shYou’ll receive the some output to review the license agreement by pressing ENTER until you reach the end.Step 5 — Activate Installation$conda listStep 6 — Set Up Anaconda Environments$conda create --name my_env python=3Step7 - Activate the new environment like so:$conda activate my_envStep8 - Launch Anaconda$anaconda-navigatorASSIGNMENT. NO. 01Title: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 employeeOutcomes:Students will be able to demonstrate calculations of employee salary.Students will be able to demonstrate different Operator & formulas.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 moreSoftware 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.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 AllowancesAllowances: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:30030Sample Output 1: Basic Pay:3000DA: 150 HRA:300 PF:360Net Pay: 3090Solution: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 ProgramThis 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.ASSIGNMENT. NO.02Title: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:Students will be able to understand basic concept of list in python.Students will be able to demonstrate different Operator & formulas on given list.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 moreSoftware 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.).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 listmy_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]# Nested Listn_list = ["Happy", [2,0,1,5]] # Nested indexing# Output: a print(n_list[0][1])# Output: 5print(n_list[1][3])947283155834Fig: List IndexingIn 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 :Create one empty list my_list. We are using one empty square bracket to create the empty list. This is a list without any items.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.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.Print the list to the user.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.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.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 n3.Read the elements of the list until n 4.Assign l[0] as maxno5.If l[i]>maxno then set maxno=l[i] 6.Increment i by 1Repeat steps 5-6 until i<nPrint the value of maximum numberConclusion: Thus, we have studied and performed operation on list in python.ASSIGNMENT. NO. 03Title: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 divisionObjective: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:Students will be able to understand basic concept of percentage calculation in python.Students will be able to demonstrate different Operator & formulas for grade and sum.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 moreSoftware 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 DescriptionThe program takes in the marks of 5 subjects and displays the grade.Problem SolutionTake in the marks of 5 subjects from the user and store it in different variables.Find the average of the marks.Use an else condition to decide the grade based on the average of the marks.Exit.Following flowchart will show basic idea about sum,average calculation in python , same logic we can apply fow percentage calculation.773552187957Fig: Flowchart for underating average, sum calculation.Conclusion: Thus, we have performed how to calculate percentage and grade, average in python.ASSIGNMENT. NO.04Title: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:Students will be able to understand basic concept of Armstrong number logic.Students will be able to demonstrate different integer number for identifying armstrong number.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 moreSoftware 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 StatementPython while LoopWhat 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.Python if Statement Syntaxif 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 Flowchart2700020119642Example: Python if Statement# If the number is positive, we print an appropriate message num = 3if 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.")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 :Read an input number using input() or raw_input().Check whether the value entered is an integer or not.Check input_num is greater than 0.Initialize a variable named arm_num to 0.Find remainder of the input number by using the mod (%) operator to get each digit in the number.Now cube each digit and add it to arm_num.Floor Divide the number by 10.Repeat steps 5. 6. 7 until the input_num is not greater than 0.If input_num is equal to arm_num, print number is ARMSTRONG.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.ASSIGNMENT. NO.05Title: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 factorsObjective: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:Students will be able to understand basic concept of number operations logic.Students will be able to demonstrate different integer number for identifying number operations.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 moreSoftware 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 ImportPython 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() functionWe 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')# Output: This sentence is output to the screena = 5print('The value of a is', a)# Output: The value of a is 5Python Data TypesEvery 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 = 5print(a, "is of type", type(a)) a = 2.0print(a, "is of type", type(a)) a = 1+2jprint(a, "is complex number?", isinstance(1+2j,complex))Python OperatorsOperators 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+35Here, + 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:x is any number such that x>=0Returns: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 NumberIn 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 Numberwe 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 Numbernumber = float(input(" Please Enter any numeric Value : ")) cube = number * number * numberprint("The Cube of a Given Number {0} = {1}".format(number, cube))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: trueInput: n = 15 Output: falseInput: n = 1 Output: falseThe 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 notnum = 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") breakelse:print(num, "is a prime number") else:print(num, "is not a prime number")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 PythonNot 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 factorialConclusion: Thus , in this experiment we have studied and performed mathematical operation on given number.ASSIGNMENT. NO.06Title: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:Students will be able to understand basic concept of number conversion.Students will be able to demonstrate different integer number for identifying number operations.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 moreSoftware 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.Convert to Binary NumberBinary 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 = 1001111Decimal value = (1*(2^6)) + (0*(2^5)) + (0*(2^4)) + (1*(2^3)) + (1*(2^2)) + (1*(2^1)) + (1*(2^0))= 79In 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 PythonTo 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.2390123101012For Example:If the binary number is 111.dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7Conclusion: Thus in this experiment we have studied and performed number conversion in python successfully.ASSIGNMENT. NO.07Title: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:Students will be able to understand basic concept of number reverse order logic.Students will be able to demonstrate different integer number for identifying number operations.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 moreSoftware 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 = 0First IterationReminder = Number %10 Reminder = 1456%10 = 6Reverse = Reverse *10 + Reminder Reverse = 0 * 10 + 6 = 0 + 6 = 6 Number = Number //10Number = 1456 //10 = 145Second IterationFrom the first Iteration the values of both Number and Reverse has been changed as: Number = 145 and Reverse = 6Reminder = Number % 10 Reminder = 145 % 10 = 5Reverse = Reverse *10+ Reminder = 6 * 10 + 5 Reverse = 60 + 5 = 65Number = Number //10 = 145 //10 Number = 14Third IterationFrom the Second Iteration of Python reverse a Number program, the values of both Number and Reverse has been changed as: Number = 14 and Reverse = 65Reminder = Number %10 Reminder = 14%10 = 4Reverse = Reverse *10+ Reminder = 65 * 10 + 4 Reverse = 650 + 4 = 654Number = Number //10 = 14//10 Number = 1Fourth IterationFrom the Second Iteration the values of both Number and Reverse has been changed as: Number = 1 and Reverse = 654Reminder = Number %10 Reminder = 1 %10 = 1Reverse = Reverse *10+ Reminder = 654 * 10 + 1 Reverse = 6540 + 1 = 6541Number = Number //10 = 1//10 Number = 0Here, For the next iteration Number = 0 so, the while loop condition will failProblem SolutionTake the value of the integer and store in a variable.Using a while loop, get each digit of the number and store the reversed number in another variable.Print the reverse of the number.Exit. Program/Source CodeHere 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//10print("Reverse of the number:",rev)Program ExplanationUser must first enter the value and store it in a variable n.The while loop is used and the last digit of the number is obtained by using the modulus operator.The last digit is then stored at the one’s place, second last at the ten’s place and so on.The last digit is then removed by truly dividing the number with 10.This loop terminates when the value of the number is 0.The reverse of the number is then printed.Runtime Test CasesCase 1:Enter number: 124Reverse of the number: 421Case 2:Enter number: 4538Reverse of the number: 8354Python Program to Reverse a Number Using FunctionsThis 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 FunctionsConclusion: Thus in this experiment we have studied and performed reverse number conversion in python successfully.ASSIGNMENT. NO.08Title: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:Students will be able to understand basic concept of even odd logic.Students will be able to demonstrate list operations.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 moreSoftware 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 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 = 5print(a, "is of type", type(a))>>>a = 2.0print(a, "is of type", type(a))>>>a = 1+2jprint(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.Examplea = [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:])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 = 2Input: list2 = [12, 14, 95, 3] Output: Even = 2, odd = 2Example 1: count Even and Odd numbers from given list using for loopIterate 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 SolutionTake in the number of elements and store it in a variable.Take in the elements of the list one by one.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.If the element is even, append it to a separate list and if it is odd, append it to a different one.Display the elements in both the lists.Exit.Program ExplanationUser must enter the number of elements and store it in a variable.User must then enter the elements of the list one by one using a for loop and store it in a list.Another for loop is used to traverse through the elements of the list.The if statement checks if the element is even or odd and appends them to separate lists.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]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.ASSIGNMENT. NO.09Title: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 palindromeCheck substringObjective: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:Students will be able to understand basic concept of string in python.Students will be able to demonstrate different operations on string.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 moreSoftware 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 immutablePython recognize as strings everything that is delimited by quotation marks (" " or ' ').String ManipulationTo manipulate strings, we can use some of Pythons built-in methods. word = "Hello World">>> print word Hello WorldAccessingUse [ ] to access characters in a string word = "Hello World"letter=word[0]>>> print letter HLengthword = "Hello World">>> len(word) 11Findingword = "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 6Counts = "Count, the numberof spaces">>> print s.count(' ') 8SlicingUse [ # : # ] to get set of letterKeep 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 characterword = "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 listSplit Stringsword = "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 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 wORLDReverse words in a given stringExample: 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: ollehThe format() Method for Formatting StringsThe 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.ASSIGNMENT. NO.10Title:To copy contents of one file to other. While copying a) all full stops are to be replaced with commasb) 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:Students will be able to understand basic concept of file handling in python.Students will be able to demonstrate file operations.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 moreSoftware 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.Hence, in Python, a file operation takes place in the following order.Open a fileRead or write (perform operation)Close the fileFile HandlingThe 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 existsIn 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) SyntaxTo 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>>> f = open("C:/Python33/README.txt") # specifying full pathWe 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.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.>>> 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 fileThis filecontains three linesWe 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 filecontains three linesThe 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. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download