0% found this document useful (0 votes)
234 views31 pages

ITC Lab Manual - Fall 2022

The document describes two Python experiments involving printing statements and loops. Experiment 1 covers PRINT statements, using \n and end="" to control output formatting. It includes exercises to print messages and shapes, calculate quadratic roots, and find triangle properties using formulas. Experiment 2 introduces comparison and logical operators. Exercises prompt the user for input and use single print statements with operators to check conditions like password matching and temperature. Experiment 3 implements conditional statements like IF-ELSE. Exercises include grading a student, finding absolute value, and defining functions to check number properties. Experiment 4 covers non-nested loops. Exercises print messages a given number of times using FOR loops, and define functions to print a name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
234 views31 pages

ITC Lab Manual - Fall 2022

The document describes two Python experiments involving printing statements and loops. Experiment 1 covers PRINT statements, using \n and end="" to control output formatting. It includes exercises to print messages and shapes, calculate quadratic roots, and find triangle properties using formulas. Experiment 2 introduces comparison and logical operators. Exercises prompt the user for input and use single print statements with operators to check conditions like password matching and temperature. Experiment 3 implements conditional statements like IF-ELSE. Exercises include grading a student, finding absolute value, and defining functions to check number properties. Experiment 4 covers non-nested loops. Exercises print messages a given number of times using FOR loops, and define functions to print a name
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Experiment # 1

Implementation of PRINT statement in


PYTHON
Things to be covered in this experiment
● Introduction to SPYDER software
● PRINT statement
● Use of \n and end=””
1. Eliminate all the syntax errors in the following code to get the output in the console
window as shown below
Code

Output

2. Write a program that prints the message as shown below. Use multiple print statements to
get the output.
Output

3. Write a program to print the diamond as shown below.


a. Use multiple print statements to complete the task.
b. Use one print statement to complete the task.
Pay attention to the number of rows, the number of asterisks (*) and the number of
spaces before * in each row.
Output
2
4. Write a program that calculates the roots of a quadratic equation 3𝑥 + 𝑥 − 2. Store the
coefficients of the quadratic equation in variables a, b and c. Then calculate the roots and
display them at the output. The formula to calculate the roots is
2
−𝑏 ± 𝑏 −4𝑎𝑐
𝑥= 2𝑎
Output

5. A right angle triangle having A = 50 metres and C = 10 metres is shown below. Write a program
to find angle 𝝰 and the side B using the two equations given below. The program should work
correctly for any values of 𝝰 and B. The output should be as shown below.

−1
α = 𝑐𝑜𝑠 (𝐶/𝐴)

𝐵 = 𝐶 × 𝑡𝑎𝑛 (α)

Output

6. Write a program to evaluate the following expression when a=10, b=5, c=15, d=20 and 𝜭 = 45°.
The program should work correctly for any values of the variables. The output should be as
shown below.
Output

7. Determine the output of the following program without using the computer.
Experiment # 2
Implementation of Comparison and Logical
operators in Python
Topics to be covered in this Lab Manual
● Conditional Statements
● Comparison and Logical Operators
Note: Use a single expression containing comparison and/or logical operators inside a single
print instruction to solve question 1 to 6. Dont use IF-ELSE or any other conditional
statement. You are not required to take input from the user in question 2 to 6.
1. Prompt the user to enter marks (only integers) of two subjects i.e. Maths and Urdu. The
program should print True if marks in both the subjects are greater than 5 otherwise
False should be printed at the output.

2. Write a program which prints True if the password entered by the user matches otherwise
False should be printed at the output. Store a password in a variable and compare it with
the password entered by the user. The password can contain digits, uppercase and
lowercase letters and special characters.

3. Suleman will only wear a jacket outside if the temperature is below 60 degrees or it is
raining. Write a program that prints True when Suleman wears the jacket otherwise prints
False. Use boolean value True to indicate to the computer that it is raining. Complete the
following program to get the output as shown below. You can only fill line 15, 16 and 17.
Don't add or delete anything else in the code.
4. Write a program which stores a number into a variable. The number could be an integer
or a floating point number. The program should print True if the number is an integer
otherwise print False at the output.

5. Write a program which calculates the sum of three numbers 0.1, 0.1, and 0.1 and
compares this sum with 0.3. What problem did you notice in this question?

6. Abdullah is happy when he gets a whatsapp message from either Ali or Umar and not
from Salman. Write a program that prints True when Abdullah is happy and False
otherwise. Use boolean value True to indicate Ali, Umar, Salman sending the message
and False otherwise.

7. Draw, on a piece of paper, the Environment Diagram for the following code. Also
determine the output. Note: min and max are built-in functions to find minimum and
maximum value in a set of numbers.

8. Determine the output of the following without using the computer. Also give reason(s).
Part a Part b Part c
Experiment # 3
Implementation of Conditional Statements in
Python
Note: Draw a flowchart before coding question number 3 to 6. Don't prompt
the user for any input in question 3 to 6.
1. Eliminate all the syntax errors in the following code that displays “The number is even”
or “The number is odd” if x is even or odd respectively.

Output

2. Implement the following recipe(algorithm) to find the grade of a student. Test your
program to determine whether it works well for x ≥ 0.
a. Prompt the user to enter the marks and store it in variable x. The marks can be a
floating point number.
b. If x is greater than 15 then display “The Grade is A”
c. If x is less than equal to 15 and greater than 10 then display “The Grade is B”.
d. If x does not satisfy any of the above mentioned conditions then print “Invalid
Input”
Flow Chart

The output should look exactly like the Case 1,2,3 shown below for different inputs
of marks
Test Case 1:
Test Case 2:

Test Case 3:

3. In the following code, write a function absolute(y) that takes a number as an argument,
calculates and returns the absolute value. The code should then print the absolute value
returned by the function The program should work correctly for any number entered by
the user. Don't use the built-in function abs( ).

Output
Test Case 1: Output when absolute(-1.5) is called

Test Case 2: Output when absolute(0) is called

Test Case 3: Output when absolute(8) is called

4. Write a program which uses a single function foo(x) to print “positive” if the number x is
positive, print “zero” if the number x is a 0 and print “negative” if the number x is
negative. Note: foo() function should not return back anything.
5. Write a program which uses a single function x(y) which returns True if y is an integer, and it
is positive, and it is even (all 3 must be True), and returns False otherwise. The returned value should
then be printed at the output. Draw a flow chart first and then code.
Test Case 1: Output when x(0) is called

Test Case 1: Output when x(-4) is called

Test Case 1: Output when x(4) is called

6. Write a function r() which takes three arguments. The first argument is the boolean
operation ( consider AND and NAND operations only ) while the rest of the two
arguments are the operands ( consider True / False only ) on which the boolean
operation is to be applied. The function r() should return the result ( in the form of True
or False ) of the boolean operation which should then be printed at the output

Test Case 1: Output when r(“and”,True,True ) is called

Test Case 2: Output when r(“nand”,True,True ) is called


7. Determine the output of the following codes without using a computer. What is the value
of x when Code 1 and 2 run completely?
Code 1 Code 2 Code 3 (Nested If-Else)

Code 4
Code 5 (The ‘return’ conundrum)
Experiment # 4
Implementation of Non-Nested Loops in
Python
Note: Draw a flowchart before coding question number 5 to 8.
1. Eliminate all the syntax and logical errors in the following code that asks the user for the
number of times “Hello World” is to be displayed and then displays it.

Test case 1:

Test case 2:

Test case 3:
2. Write a function f() which prints a name ‘n’ times. Follow steps A, B and C to get the required
output
A. Write a code using for-loop to print “ali” 5 times.
B. Now put the code you wrote in part A into the function f(name) shown below. The argument of
the function f() could be any name.

Test case 1: The following output comes when f(“ali”) is called

Test case 2: The following output comes when f(“cat”) is called

C. Now add another parameter ‘n’ to the function f(name) to print the name ‘n’ times. For
example f(“ali”, 3) should print ‘ali’ 3 times. Another example: f(“yahya”, 10) should print yahya 10 times.
Submit part C code only by the name e4t2.py.

Test case 1: The following output comes when f(“ail” , 5) is called


Test case 2: The following output comes when f(“Parrot”,3) is called

Notice how we approached this problem of writing a complete function. First we wrote code without any
user-defined function in part A. Then we wrote the code of part A inside the function f() (Part B). Then
we added a new parameter ‘n’ to the function. Follow this approach for writing functions!!!

3. Write a function print_even(n) that prints first ‘n’ integers that are even and divisible by 6. The
function should also display the number of such integers. To solve this problem, breakdown this
complex problem into simpler problems (Parts A, B, C and D below) and gradually modify them
as required.

A. Write a code to print the first 5 integers including 0 using a for loop.

B. Now write a function print_even(n) which when called should print first ‘n’ integers including
0. For example print_even(5) should give the following output.

Test case 1: The following output comes when print_even(5) is called

Test case 2: The following output comes when print_even(3) is called

C. Now modify the definition of the function print_even() in part B so that it prints integers that
are even and divisible by 6. For example when print_even(50) is called, the following output
should appear
Test case 1: The following output comes when print_even(50) is called

Test case 2: The following output comes when print_even(30) is called

D. Now modify the function print_even() in part B so that it also prints the number of integers
that are even and divisible by 6. For example when print_even(50) is called, the following output
should appear. Submit part D code only by the name e4t3.py

Test case 1: The following output comes when print_even(50) is called

Test case 2: The following output comes when print_even(30) is called

Notice how we approached this problem by first solving the simplest version of it (Part A) and
then gradually increasing its complexity to get the required output!!! You should also use this
approach to write complex programs.Of course, before writing a program you should know its
algorithm first!!
4. Complete and then place the whole code inside the function baz() which when called should
display the output shown below. The function baz() should neither take any argument nor return
back anything.

Output

5. Steps a to e below are part of an algorithm (algo) to find the absolute of a number three
times. Do you think the program will work correctly or the order of the steps should be
rearranged to correctly run the program? If so, rearrange the steps below. Convert the
following algorithm into a flow chart. Then start to code.

Algorithm for question 5

Repeat the following steps a to c 3 times using a for-loop:

a. Display the message “The absolute of x is ___” where ___ is the absolute of x.
b. Prompt the user to enter the number, and store it in variable x.
c. Call the function absolute(x), which takes x as argument, to find and return the
absolute of x.

Write the following steps inside the definition of the function absolute(y). Do you
think the steps below need to be rearranged?

d. Return y
e. If y is negative, then multiply it by -1 and store it in y.
Test case 1:

Test case 2:

6. Write a program that prompts the user to enter a number and then that number is
displayed at the output as it is.The program should continue to prompt the user and
display the number as long as the number is less than 5. The program should print “end”
and then stop when the user enters any number greater than 5. Can a loop be used to
solve this problem? If so, which loop will you prefer, for or while? Give reasons. Don't
write any user-defined function to solve this problem.
Test Case 1:
Test Case 2:

7. Write a function foo(x) to determine and return the number of 1s, 2s and 3s in the number
x. The program should work correctly for any number containing only the digits 1, 2 and
3. The output should look like as shown below. Follow the steps given in the algorithm
below. The first 3 steps in the algorithm below are for the function foo().

Algorithm

a. Store the number as a string in variable s


b. While iterating over variable s
If the character in s is 1, increase variable a by 1s
Else if the character in s is 2, increase variable b by 1
Else if the character in s is 3, increase variable c by 1
c. Return a, b and c.
d. Display the four lines as shown in the output below.

Test Case 1: The following output comes when a=”1233”

Test Case 2: The following output comes when a=”11112333”


Test Case 3: The following output comes when a=”12213233”

8. You can hide a secret message in a piece of text by setting a specific character as a key.
Place the key before every letter in the message, then fill in extra (non-key) letters
between key-letter pairs to hide the message in noise. For example, to hide the message
"computer" with the key "q", you would start with "computer", turn it into
"qcqoqmqpquqtqeqr", and then add extra letters as noise, perhaps resulting in
"orupqcrzypqomqmhcyqpwhhqutqtxtqeyeqrpa". To get the original message back out,
copy every letter that occurs directly after the key, ignoring the rest.

Write a function getSecretMessage(s, key) that takes a piece of text holding a secret
message and the key to that message and returns the secret message itself. For example, if
we called the function on the long string above and "q", it would return "computer".

Test Case 1: The following output comes when


getSecretMessage(“qcqoqmqpquqtqeqr”,”q”) is called

Test Case 2: The following output comes when


getSecretMessage(“orupacrzypaomamhcyapwhhautatxtaeyearp”,”a”) is called
9. Determine the output of the following codes without using the computer. What does the
function mystery() do in code 3 ? Give answers on a piece of paper.

Code 1 Code 2 Code 3

10. What is printed when you call f(3, 6) in the following code? Give answers on a piece of paper.

a. Is it possible to call f on a pair of valid arguments such that it only prints ” - - -” to the console? If
yes, give an example pair of arguments and generalize your answer. If no, explain why not.

b. Is it possible to call f on a pair of valid arguments such that the call gets stuck in an infinite loop?
If yes, give an example pair of arguments and generalize your answer. If no, explain why not.
Experiment # 5
Formatting, Environment Diagram Involving
a Function and Debugging

First you have to do question no 2, 3, 9 and 10 of experiment 4 before starting this experiment.

1. Without using the computer


a. Draw, on your ITC Lab register, one environment diagram for code no. 1 when it is
completely executed.
b. Draw, on your ITC Lab register, one environment diagram for code no. 2 just before the
function double(3) returns its value.
c. Draw, on your ITC Lab register, one environment diagram for code no. 2 just before the
function hmm(wow) returns its value.
d. Draw, on your ITC Lab register, one environment diagram for code no. 2 after the code
runs completely.

Code 1 Code 2

2. Complete the following code using f-strings to get the output shown below. You are not allowed
to use space(s) inside the f-string at line no 12 to 14. Variables x and y have the percentage of ITC
and math respectively.
Output

Before doing questions 3 to 6, watch this video

3. The following code contains three errors. Copy the code from this file and paste into the coding
area of the Spyder software. Follow the steps below
a. Run the code and write the error message on your lab register. What do you understand
from the error message? Did the error message display the line number at which the
error is present? Correct this mistake.
b. Now run the code again and write the error message on your lab register. What do you
understand from the error message? Did the error message display the line number at
which the error is present? Correct this mistake.
c. Now run the code again and write the error message on your lab register. What do you
understand from the error message? Did the error message display the line number at
which the error is present? Correct this mistake.
d. Determine the output of the code, after removing the errors you caught in parts a to c,
without using the computer.
4. The function absolute(y) is supposed to return the absolute of a number. But upon running the code it
gives incorrect output. Follow the steps below to find the cause of the incorrect output

a. Go through the code step by step (known as code tracing) using a pen and a paper. Will
the code work for all numbers? If not, why? What is the problem?

b. Assume you were unable to go through the code (due to tiredness or

having watched maybe ) and spot the mistake using a pen and page. Use
pythontutor.com to trace the code step by step. Did each step run according to your
expectation? If not, which step(s) are causing incorrect output to appear. Give reasons.
c. What type of error the code contains - - - Syntax, Runtime or Logical. Give a reason.

5. The following code, when executed, gives incorrect output. Follow the steps below to correct the
code. Follow the steps below to find the cause of the incorrect output

a. Go through the code step by step (code tracing) using a pen and a paper and write the
output. Did you spot the mistake?
b. Assume you were unable to go through the code and spot the mistake using a pen and
page. Use pythontutor.com to trace the code step by step. Did each step run according
to your expectation? If not, which step(s) are causing incorrect output to appear. Give
reasons.
c. What type of error the code contains - - - Syntax, Runtime or Logical. Give a reason.
6. The following code is supposed to print the number of spaces in the password. Do you think the code
prints the correct number of spaces in the password? To answer this, follow the steps below.

a. Go through the code step by step (code tracing) using a pen and a page. What is the expected
output and what did you get actually?
b. Assume you were unable to go through the code and spot the mistake using a pen and page. Use
pythontutor.com to trace the code step by step. Did each step run according to your
expectation? If not, which step(s) are causing incorrect output to appear. Give reasons.
c. What type of error the code contains (if any) - - - Syntax, Runtime or Logical. Give a reason.

7. What lessons have you learnt by doing questions 4 to 6? Explain briefly.


Experiment # 6
Implementation of Nested Loops in Python
Draw flowchart for question 5 and 6.
1. Determine the output of the following code without using the computer.

2. Complete the following program to get the output as shown below.

Output
3. Convert the following flowchart to python code to get the output as shown below

Output
4. Using the algorithm shown below, write the function PrimeFactors(x) which takes a
positive integer x and prints all of its prime factors in a nice format. A prime factor is a
number that is both prime and evenly divides the original number (with no remainder).
So the prime factors of 70 are 2, 5, and 7, because 2 * 5 * 7 = 70. Note that 10 is not a
prime factor because it is not prime, and 3 is not a prime factor because it is not a factor
of 70. Prime factors can be repeated when the same factor divides the original number
multiple times; for example, the prime factors of 12 are 2, 2, and 3, because 2 and 3 are
both prime and 2 * 2 * 3 = 12. The prime factors of 16 are 2, 2, 2, and 2, because 2 * 2 *
2 * 2 = 16. We'll display repeated factors on a single line as a power expression; for
example, 16 would display 2 ** 4, because 2 is repeated four times. Here's a high-level
algorithm to solve this problem. Start by iterating through all possible factors. When you
find a viable factor, repeatedly divide the number by that factor until it no longer evenly
divides the number. Our algorithm (pseudocode) looks something like this:
1. Repeat the following procedure over all possible factors (2 to x)
a. If x is evenly divisible by the possible factor
i. Set a number count to be 0
ii. Repeat the following procedure until x is not divisible by the possible
factor
1. Set count to be count plus 1
2. Set x to x divided by the factor
iii. If the number count is exactly 1
1. Print the factor by itself
iv. If the number count is greater than 1
1. Print "f ** c", where f is the factor and c is the count
Output
5. Write a program that prompts the user to enter the number of rows of a pyramid and it
then displays the pyramid at the output according to the number of rows given by the
user. Use nested for-loops to get the output.
Output Sample 1

Output Sample 2

6. Write a program that prompts the user to enter the number of rows of a diamond and it
then displays the diamond at the output according to the number of rows given by the
user. Use nested for-loops to get the output.

Output Sample 1

Output Sample 2
Experiment # 7
Implementation of Lambda Functions and Higher Order
Functions in Python
1. Determine the output of the following codes without using the computer. Code 2 and 3
could be traced without using the environment diagram.
For code 1
1. Draw the environment diagram when f(x+n) is about to be called at line 51. What will
be applied to (x+n) at line 51 i.e. what f is evaluated to at line 51?
2. When f(x+n) is called, what value of n will be used? Give reason
3. Draw the environment diagram when the computer is about to exit the function f(f,x)
after running it completely.
4. Draw a maximum of 4 environment diagrams which are created during the execution
of line 54.

Code 1 Code 2

Code 3
2. Consider the following two functions, which all compute summations. The first,
sum_naturals, computes the sum of natural numbers up to n:
>>> def sum_naturals(n):
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total

>>> sum_naturals(100)
5050

The second, sum_cubes, computes the sum of the cubes of natural numbers up to n.
>>> def sum_cubes(n):
total, k = 0, 1
while k <= n:
total, k = total + k*k*k, k + 1
return total

>>> sum_cubes(100)
25502500

These two functions clearly share a common underlying pattern. They are for the most part
identical, differing only in name and the function of k used to compute the term to be added.
We could generate each of the functions by filling in slots in the same template:

l
The presence of such a common pattern is strong evidence that there is a useful abstraction
waiting to be brought to the surface. Each of these functions is a summation of terms. As
program designers, we would like our language to be powerful enough so that we can write a
function that expresses the concept of summation itself rather than only functions that
compute particular sums. We can do so readily in Python by taking the common template
shown above and transforming the "slots" into formal parameters. Complete the above
program which should print
● summation of cubed integers upto n when summation(n,cube) is called, where n is
3 3 3
any integer. For example, summation(3,cube) should return 1 + 2 + 3 which is
36
● summation of natural integers upto n when summation(n,naturals) is called, where n
is any integer. For example, summation(3, naturals) should return 1 + 2 +3
which is 6.

3. Write a function mutliply_by(m) which takes in a number m and returns a function


multiply(n) that can take in a single integer n as a parameter. This returned function
multiply(n) should return the product of m and n when called. For example,
times_three(5) should print the product of 3 and 5. Alternatively, multiply_by could
be called directly to print the product of 3 and 10 as shown below. Note: Delete lines
89 to 91 before submitting the file.
4. Write a function make_keeper(n) that takes in a number n and returns a function that
can take in a single parameter cond. When we pass in some condition function cond
into this returned function, it will print out numbers from 1 to n where calling cond on
that number returns True. For example, calling make_keeper(6)(is_even) should print
all even numbers from 2 to 6. Note: Delete line 76 before submitting the file.

You might also like