0% found this document useful (0 votes)
1K views76 pages

2020f Bse 013 P Fund Lab File

This document is a lab file for the course Programming Fundamentals at Sir Syed University of Engineering & Technology. It contains the student's name, roll number, section, and semester. The file also lists 13 labs completed by the student over the course of the semester, along with the date, lab description, and signature of the lab instructor for each. The labs cover topics like data types, variables, operators, input/output, conditional statements, loops, functions, lists, files, and more.

Uploaded by

Laraib Shahzad
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)
1K views76 pages

2020f Bse 013 P Fund Lab File

This document is a lab file for the course Programming Fundamentals at Sir Syed University of Engineering & Technology. It contains the student's name, roll number, section, and semester. The file also lists 13 labs completed by the student over the course of the semester, along with the date, lab description, and signature of the lab instructor for each. The labs cover topics like data types, variables, operators, input/output, conditional statements, loops, functions, lists, files, and more.

Uploaded by

Laraib Shahzad
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/ 76

Sir Syed University of Engineering & Technology (SSUET)

Software Engineering Department


Sir Syed University of Engineering &Technology, Karachi
Main University Road, Karachi 75300
http://www.ssuet.edu.pk

Course: Programming Fundamental

Name: MUHAMMAD MAAZ


Roll Number: 2020F-BSE-013
Section: A
Semester: 1

LAB FILE

Lab Teachers:
Sr Adnan Afroz
Ms. Fizah Sohail
Sir Syed University of Engineering & Technology
Software Engineering Department Fall 2020 Batch
SWE-102 Programming Fundamental
Fall Semester -- 2020
Semester -- 1st
Lab Index
Roll No.: 2020F-BSE-013
Student Name: Muhammad Maaz
Section: A
Lab
Date Lab Description Signature Remarks
#
To become familiar with the Python
1 06-Oct-20 Programming by using an Integrated
Development Environmen
Implement different type of data
types,variables
2 13-Oct-20 and operators used in python.

Taking input from user and controlling


3 20-Oct-20 output position.

To get familiar with the concept of


conditional
4 27-Oct-20 statement for simple decision making.

To get familiar with different type of loop.


5 03-Nov-20

Working on nested statement and controol loop

6 10-Nov-20 iteraton using break and continue.

Create a python function using different

7 17-Nov-20 argument types.

Exploring list/arrays in python programming


8 08-12-20
Sir Syed University of Engineering & Technology
Software Engineering Department 2021 Batch
SWE 102 Programming Fundamental
Fall Semester -- 2020
Semester -- 1st
Lab Index
Roll No.: 2020F-BSE-013
Student Name: Muhammad Maaz
Section: A
Lab
Date Practical Description Signature Remarks
#
Searching and sorting data in the form of list

9 15-12-20

Getting familiar with other data storing

10 15-12-20 Techniques- Tuple and Dictionary

Getting familiar with the environment

11 22-12-20 for using modules and packages

Working on the strings formatting

12 22-12-20

To explore methods to access,

13 29-12-20 open/close, modes contained

in external files
LAB # 01

INTRODUCTION

OBJECTIVE
To become familiar with the Python Programming by using an Integrated Development
Environment

EXERCISE
A. Create a file named lab1.py. Write the following code in the file. Execute it and show
the output. (You can use the Snipping Tool to take a snapshot of your output window).
1. Code:
# My first program
print("Welcome in the world of programming! \n")

Output:

2. Code:
#My second program
print("Welcome in the ")
print("world of programming!
\n")
Output:

B. Write a program in Python language that prints your bio-data on the screen. Show
your program and its output.
3. Code.
'''
#bio data program
BIODATA
NAME
ID
TECHNOLOGY
BATCH
SECTION
'''

print("\tBIODATA\n")
print("NAME=MUHAMMAD MAAZ\n")
print("ID= 2020F-SE-013\n")
print("TECHNOLOGY= SOFTWARE ENGINEERING\n")
print("BATCH=FALL-2020\n")
print("Section= A\n")

Output:
LAB # 02

VARIABLES AND OPERATORS

OBJECTIVE
Implement different type of data types, variables and operators used in Python.

EXERCISE
A. Point out the errors, if any, in the following Python statements.

1. x=5:
print(x)

x=5:
^
Syntax Error: invalid syntax

“This colon(:) causing the error”

2. 1TEXT = "SSUET"
NUMBER = 1
print(NUMBER+ TEXT)

1TEXT = "SSUET"
^
Syntax Error: invalid syntax

“The variable is starting with numeric character and a,(,) must be


used when dealing with integers”

3. a = b = 3 = 4
a = b = 3 = 4
^
Syntax Error: can’t assign to literal

“Two values can not be assigned to a single variable.”


B. Evaluate the operation in each of the following statements, and show the
resultant value after each statement is executed.

1. a = 2 % 2 + 2 * 2 - 2 / 2;

CODE:
#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
a = 2 % 2 + 2 * 2 - 2 / 2;
print(a)
OUTPUT:

2.b = 3 / 2 + 5 * 4 / 3 ;

CODE:
#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
b = 3 / 2 + 5 * 4 / 3 ;
print(b)

OUTPUT:
3.c = b = a = 3 + 4 ;
CODE:
#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
c = b = a = 3 + 4 ;
print(c)

OUTPUT:

C. Write the following Python programs:

1. Write a program that calculates area of a circle 𝐴 = 𝜋𝑟2. (Consider r = 50).


CODE:
#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
pi = 3.14 #pi
r = 50 #radius
#area of circle
area=pi*r**2
print("Area of Circle")
print("pi=" , pi)
print("radius=50cm")
print("Formula of Area of Circle : pi*r**2")
print(area, "sq cm")

OUTPUT:

2. Write a program that performs the following four operations and prints their result on
the screen.
a. 50 + 4
b. 50 – 4
c. 50 * 4
d. 50 / 4
CODE:

#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
a=50
b=4
print("50+4=",a+b)
print("50-4=",a-b)
print("50*4=",a*b)
print("50/4=",a/b)

OUTPUT:

3. Write a Python program to convert height (in feet and inches) to centimeters.
Convert height of 5 feet 2 inches to centimeters.

• First, convert 5 feet to inches: 5 feet × 12 inches/foot = 60 inches


• Add up our inches: 60 + 2 = 62 inches
• Convert inches to cm: 62 inches × 2.54 cm/inch = 157.48 cm

CODE:
#Muhammad Maaz
#ROLL N0: 2020F-BSE-013
f=5
i=2
m=(f*12)+i
print("Height in cm =",(m*2.54))

OUTPUT:
4. Write a program to compute distance between two points by creating
variables (Pythagorean Theorem)
Distance =((x2−x1)^2+(y2−y1)^2)^1/2

CODE:
#Muhammad Maaz
#ROLL NO: 2020F-BSE-013
x1=22
x2=17
y1=14
y2=28

print("d=",((x2-x1)**2+(y2-y1)**2)**(1/2))

OUTPUT:
LAB # 03
CONSOLE INPUT AND OUTPUT

OBJECTIVE
Taking input from user and controlling output position.

EXERCISE
A. Point out the errors or undefined/missing syntax, if any, in the following
python programs.

1. print("Hello \b World!")
There is no error

2. first_number = str ( input ("Enter first number") )


second_number = str ( input ("Enter second number") )

sum = (first_number + second_number)


print("Addition of two number is: ", sum)
Str causing the error it doesn’t sum the two number. If we apply
int in the first and second line the number will be added.

3. age = 23
message = "Happy " + age + "rd Birthday!"
print(message)
The sum (+) causing the error. If we apply comma (,) instead of
sum (+) the program will run.

B. What would be the output of the following programs:

1. a=5
print("a =", a, sep='0', end=',')

Code:
#Muhammad Maaz
#2020F-BSE-013
a=5
print("a =", a, sep='0', end=',')
OUTPUT:

2. name = input("Enter Employee Name")


salary = input("Enter salary")
company = input ("Enter Company name")
print("Printing Employee Details")
print ("Name", "Salary", "Company")
print (name, salary, company)

CODE:
#Muhammad Maaz
#2020F-BSE-013
name = input("Enter Employee Name")
salary = input("Enter salary")
company = input ("Enter Company name")
print("Printing Employee Details")
print("Name", "Salary", "Company")
print(name, salary, company)

OUTPUT:
3. n1=int(input('"enter n1 value'))
n2=int(input('enter n2 value'))
CODE:
#Muhammad Maaz
#2020F-BSE-013
n1=int(input('enter n1 value:'))
n2=int(input('enter n2 value:'))

OUTPUT:

C. Write Python programs for the following:

1. Write a program to print a student’s bio data having his/her Date of birth, Roll no,
Section, Percentage and grade of matriculation and Intermediate. All the fields should
be entered from the console at run time.

CODE:
#Muhammad Maaz
#2020F-BSE-013
#BIO DATA PROGRAM
#Input Statement
name = input("Enter your name:")
db = input("Enter your date of birth:")
age = input("Enter your age:")
roll_no = input("Enter your roll no:")
sec = input("Enter your section:")
mat_per = float(input("Enter you Matric percentage:"))#we use float because in pyhton
input is taken as string by default.
mat_grade = input("Enter your Matric grade:")
int_per = float(input("Enter your Inter percentage:"))
int_grade = input("Enter your Inter grade:")
#Print Statement
print(name)
print(db)
print(age)
print(roll_no)
print(sec)
print(mat_per)
print(mat_grade)
print(int_per)
print(int_grade)

OUTPUT:

2. Write a program that asks the user what kind of food they would like. Print a message
about that food, such as “Let me see if I can find you a Chowmein”. Food name must
be in uppercase. (hint: use upper( ) for food name)
CODE:
#Muhammad Maaz
#2020F-B SE-013
food_name = input ("what kind of food does you like:")
print("Let me see if I can find you a",food_name.upper())

OUTPUT:

3. Take the marks of 5 courses from the user and calculate the average and percentage,
display the result:
Eachcourse=50 marks
Total_marks= course1+course2+course3+course4+course5
average=Total_marks/5
percentage=(Total_marks x 100)/250

CODE:
#Muhammad Maaz
#2020F-BSE-013
# A program to display Exam result.
Phy = int(input("Enter your Physics Number:"))
Math = int(input("Enter your Mathematics Number:"))
Comp = int(input("Enter your Computer Number:"))
Isl = int(input("Enter your Islamiat Number:"))
Urdu = int(input("Enter your Urdu Number:"))
print("Each course has maximum 50 marks")
Total_marks = Phy+Math+Comp+Isl+Urdu
print("Total Marks=", Total_marks)
average = Total_marks/5
print("average=", average)
percentage = (Total_marks*100)/250
print("percentage=",percentage,"%")
OUTPUT:
LAB # 04

DECISIONS

OBJECTIVE
To get familiar with the concept of conditional statement for simple decision making.

EXERCISE

A. Point out the errors, if any, in the following Python programs.


1. Code
a = 500,b,c;
if ( a >= 400 ):
b = 300
c = 200
print( "Value is:", b, c )

This code is causing error because variable b& c are not defined.

2. Code

&number = eval(input("Enter an integer: ")) print(type(number))


if number % 5 == 0
print("HiFive")
else:
print ("No answer")

1.‘&’ This is causing the error because program can not run because symbols like &,$ etc
variables like can not be started with symbols or numbers
2. Another error is causing due to semicolon is not at the end of if and else command.
3. Code
if score >= 60.0
grade = 'D'
elif score >= 70.0
grade = 'C'
elif score >= 80.0
grade = 'B'
elif score >= 90.0
grade = 'A'
else:
grade = 'F'

In this program there are two errors first is semicolon is not at the end of ‘if’ and ‘elif’
command and second is due to wrong indentation.

B. What would be the output of the following programs:


1. CODE:

#Muhammad Maaz
#2020F-BSE-013
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")

Output:
2. CODE:

#Muhammad Maaz
#2020F-BSE-013
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

OUTPUT:

3. CODE:

#Muhammad Maaz
#2020F-BSE-013
age = 15
if age < 4:
price = 0
elif age < 18:
price = 1500
else:
price = 2000
print("Your admission cost is Rs" + str(price) + ".")

OUTPUT:
C. Write Python programs for the following:

1. Any integer is input through the keyboard. Write a program to find out whether it is an
odd number or even number.

CODE:

#Muhammad Maaz
#2020F-BSE-013
no=input("Enter the number:")
print(no)
no_type=int(no)%2
odd_no=1
if odd_no==no_type:
print("This is odd number")
else:
print("This is even number")

OUTPUT:

2. Write a program that asks for years of service and qualification from the user and
calculates the salary as per the following table:

Years of Service Qualifications Salary


>= 10 Masters 150,000
>= 10 Bachelors 100,000
< 10 Masters 100,000
< 10 Bachelors 70,000

CODE:

#Muhammad Maaz
#2020F-BSE-013

qal = input("ENTER QUALIFICATION = ").upper()


ys =int(input("ENTER YEARS OF SERVICE = "))

if(ys >=10) and (qal== "MASTERS"):


print("150,000 salary")
elif(ys >=10) and (qal== "BACHELORS"):
print("100,000 salary")
elif(ys <10) and (qal== "MASTERS"):
print("100,000 salary")
elif(ys <10) and (qal== "BACHELORS"):
print("70,000 salary")
else:
print("other salary")

OUTPUT:

3. Write an if-elif-else chain that determines a person’s stage of life, take input value for the
variable age, and then apply these conditions:

• If the person is less than 2 years old, print a message that the person is a baby.
• If the person is at least 2 years old but less than 4, print a message that the person is a
toddler.
• If the person is at least 4 years old but less than 13, print a message that the person is a kid.
• If the person is at least 13 years old but less than 20, print a message that the person is a
teenager.
• If the person is at least 20 years old but less than 65, print a message that the person is an
adult.
• If the person is age 65 or older, print a message that the person is an elder.
CODE:

#Muhammad Maaz
#2020F-BSE-013

age= eval(input("ENTER YOUR AGE:"))


if (age>=0) and (age< 2):
person= ("a baby")
elif(age>=2) and (age< 4):
person= ("a toddler")
elif(age>=4) and (age< 13):
person= ("a kid")
elif(age>=13) and (age< 20):
person= ("a teenager")
elif(age>=20) and (age< 65):
person= ("a adult")
elif(age>=65) and (age< 100):
person= ("a elder")
else:person=("Enter a valid age")
print("you are", person)

OUTPUT:
LAB # 05

ITERATION WITH LOOPS

OBJECTIVE

To get familiar with the different types of loops.

EXERCISE
A. Point out the errors, if any, in the following Python programs.
1. Code:
for(;;)
{
printf("SSUET")
}

1. This (; ;) causing the error. The syntax is not valid.


2. The second error is the variable ‘f’ is not defined.

2. Code:
count = 4
while n < 8
count = count + 3:
print(count)

1. The variable ‘n’ is not defined.


2. Indentation error in ‘Print’ and there is no “” in “print(count)” this also cause
error.
3. Another error is there is semicolon after this “count = count + 3:” this also
cause the error.

3.Code
for v in range(4:8)
print(v)

1. The error is due to “(4:8)” semicolon is not come in between two numbers
it come after for condition.
2. Another error is due to “print(v)” this is not in the loop that’s also
causing the error.
B. What will be the output of the following programs:
1. CODE:

#Muhammad Maaz
#2020F-BSE-013

i=1
while i < 10:
if i % 2 == 0:
print(i,end=" ")
i += 1

OUTPUT:

2. CODE:

#Muhammad Maaz
#2020F-BSE-013

i=1
while i>0:
print(i,end=" ")
i=i+1

OUTPUT:

\
3. CODE:
#Muhammad Maaz
#2020F-BSE-013

for v in range(3, 9, 2):


print(v)

OUTPUT:

C. Write Python programs for the following:

1. Write a program that prints the first 10 natural numbers and their sum using ‘for
loop’.
Sample output:
The first 10 natural number are :
1 2 3 4 5 6 7 8 9 10
The Sum is : 55

CODE:

#Muhammad Maaz
#2020F-BSE-013
print("Using for Loop")
print("Sum of first 10 natural numbers")
num = 10
sum = 0
for num in range(0, num+1, 1):
sum = sum+num
print("Sum of first ", num, "Numbers is: ", sum )
print("Using while Loop")
print("Sum of first 10 natural numbers")
num = 1
sum = 0
while num<=10:

sum= sum+num
num+= 1
print("The sum is", sum)

OUTPUT:

2. Write a program to print the multiplication table of the number entered by the user.
The table should get displayed in the following form.
29 x 1 = 29
29 x 2 = 58

29 x 10 = 290

CODE:

#Muhammad Maaz
#2020F-BSE-013

print("Using for Loop")


tab = 29
for no in range(1, 11):
print(tab, "x", no, "=", tab*no)

print("Using while Loop")


no=1
tab=29
while (no <= 10):
print(tab, "x", no, '=', tab*no)
no+=1

OUTPUT:

3. Write a program that take vowels character in a variable named “vowels” then
print each vowels characters in newline using ‘for loop’.

CODE:
#Muhammad Maaz
#2020F-BSE-013

character= input("Enter Any Thing:")


character= character.upper()
print("VOWELS ARE")
a = e = i = o = u= 0

for vowel in character:


if (vowel)=="a" or (a!=1):
a=1
print("a", end= ",")
elif (vowel=="e") or (e!=1):
e=1
print("e", end= ",")
elif (vowel=="i") or (i!=1):
i=1
print("i", end= ",") 9.1

elif (vowel=="o") or (o!=1):


o=1
print("o", end= ",")
elif (vowel=="u") or (u!=1):
u=1
print("u", end= ",")

OUTPUT:

9.1 you have made your code complex!


LAB # 06
NESTED STATEMENTS, BREAK
AND CONTINUE STATEMENTS

OBJECTIVE
Working on nested statements and control loop iteration using break and continue.

EXERCISE

A. Point out the errors, if any, in the following Python programs.


1. CODE:
prompt = "\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)" while
True: city = str(input(prompt)) if city == quit:
break; else: print("I'd love to go to " ,
city.title() , "!")

OUTPUT:
The error in this program is in the break statement because the print statement use the
break line and the print line use the invalid syntax that’s why program is giving the
error.
2. CODE:
if x>2:
if y>2:
z=x+y
print(“z is”, y)
else
print(“x is”, x)

OUTPUT:
In this program there is an indentation error. 4.1

3. CODE:
balance = int(input("enter your
balance1:")) while true: if balance
<=9000: continue;
balance = balance+999.99 print("Balance
is", balance)

OUTPUT:
In this Program the error is of indentation both loops are written in one line. And the code
written half in both line.

B. What will be the output of the following programs:


1. CODE:
i = 10 if (i
== 10):
# First if statement if (i <
15): print ("i is smaller
than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true if (i < 12):
print ("i is smaller than 12 too")
else: print ("i is greater than
15")
CODE:
#Muhammad Maaz
#2020F-BSE-0134
i=10 if (i
==10):
# first if statementif(i<
15):print("i is smaller
than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true if(i<12):

print("i is smaller than 12 too")


else: print("i is greater than
15")

OUTPUT:

2. Code
i = 1 j = 2 k = 3 if i i = 1 j = 2 k = 3
> j: if i > k: if i > j: if
print('A') else: i> k:
print('B') print('A')
else:
print('B')

CODE:
#Muhammad Maaz
#2020F-BSE-013
i = 1 j = 2 k = 3 if i
> j: if i > k:
print('A') else:
print('B')

i=1j=2k=3
if i > j: if
i> k:
print('A')
else:
print('B')
OUTPUT:

3. Code
# nested for loops for
i in range(0, 5): for
j in range(i):
print(i, end=' ')
print()

CODE:
#Muhammad Maaz
#2020F-BSE-013
# nested for loops for
i in range(0, 5): for
j in range(i):
print(i, end=' ')
print()

OUTPUT:
C. Write Python programs for the following:

1. Write a program to add first seven terms twice of the following series:

CODE:

#Muhammad Maaz
#2020F-BSE-013
sum = 0
for m in range (1,8):
fact = 1
for index in range (1,(m+1)):
fact = fact * index
fact_f = m/fact
sum = sum + fact_f

print("Sum of first seven terms of Factorial is:",sum))

OUTPUT:

2. Write a program to print all prime numbers from 900 to 1000.


[Hint: Use nested loops, break and continue]
CODE : #Muhammad Maaz
#Muhammad Maaz
#2020F-BSE-013
#2020F-BSE-013
print("PRIME NUMBERS BETWEEN 900
print("PRIME NUMBERS BETWEEN 900
TO 1000")
TO 1000")
a = 900
a = 900
b = 1000
b = 1000
print("Prime numbers between", a, "and", b,
print("Prime numbers between", a, "and", b,
"are:", )
"are:", )
for num in range(a, b + 1, ):
for num in range(a, b + 1, ):
# all prime numbers are greater than 1
# all prime numbers are greater than 1
if num > 1:
if num > 1:
for i in range(2, num ):
for i in range(2, num ):
if (num % i) == 0:
if (num % i) == 0:
continue
break
else:
else:
print(num, end=" ")
print(num, end=" ")

OUTPUT:
(BREAK CONDITION):

(CONTINUE CONDITION):
3. Write a program to display multiplication table(1-5) using nested looping
Sampled output:[hint: '{ } ' .format(value)]
02 X 01 = 02

CODE:
#Muhammad Maaz
#2020F-BSE-013
for i in range (1,6):
for j in range (1,11):
print(i,"x",j,"=",i*j)
print("\n")

OUTPUT:

9.1

4.1 incomplete statement!

9.1 no screenshots of output in exercise A!


LAB # 07

FUNCTIONS

OBJECTIVE

Create python function using different argument types.

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python
programs.
1. Code
define sub(x, y)
return x + y

Error:
The error is in this program is that parameter is in wrong text. That’s why program causing
the error . 4.1

2. Code
define describe_pet(pet_name, animal_type='dog'):
print("\nI have a " , animal_type ,".")
print("My " , animal_type + "'s name is " , pet_name +
".")

Error:
The error is in this program is the use of ‘pet’ in def statement and also in parameter
that’s why program causing the error.
3. Code
def type_of_int(i):
if i // 2 == 0:
return 'even'
else:
return 'odd'

Error:
The error is in this program is that indentation in written statement.

B. What will be the output of the following programs:


1. CODE:
#Muhammad Maaz
#2020F-BSE-013
def test(a):
def add(b):
a =+ 1
return a+b
return add
func = test(4)
print(func(4))

OUTPUT:

2. CODE:
#Muhammad Maaz
#2020F-BSE-013

def return_none(): return


print(return_none())

OUTPUT:
3. CODE:
#Muhammad Maaz
#2020F-BSE-013
def test_range(n):
if n in range(3,9):
print( n,"is in the range")
else :
print("The number is outside the given range.")
test_range(7)

test_range(4)

OUTPUT:

C. Write Python programs for the following:

1. Write a function called favorite_book() that accepts one parameter, title. The function
should print a message, such as One of my favorite books is Alice in Wonderland. Call
the function, making sure to include a book title as an argument in the function call.

CODE:
#Muhammad Maaz
#2020F-BSE-013
def favorite_book(Tittle):
print("One of my favorite books is",Tittle)
favorite_book("Computer Studies")
favorite_book("Pakistan Studies")

OUTPUT:
2. Write a function called max( ), that returns the maxium of three integer numbers.

CODE:
#Muhammad Maaz
#2020F-BSE-013
def maximum(x, y, z):
var = [x, y, z]
return max(var)

x = 107
y = 244
z = 987
print(maximum(x, y, z))

OUTPUT:

3. Write a Python program to find GCD of two numbers

CODE:
#Muhammad Maaz
#2020F-BSE-013
# Python Program to find GCD of Two Numbers using While loop
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
num3 = int(input("Enter 3rd number: "))
i=1
while(i <= num1 or i <= num2 or i<= num3):
if(num1 % i == 0 or num2 % i == 0 or num3 % i == 0):
gcd = i
i=i+1
print("GCD is", gcd)

OUTPUT:

4. Write a function called describe_city() that accepts the name of a city and its country.
The function should print a simple sentence, such as Reykjavik is in Iceland. Give the
parameter for the country a default value. Call your function for three different cities, at
least one of which is not in the default country.

CODE:
#Muhammad Maaz
#2020F-BSE-013
def describe_city(city, country='ENGLAND'):
"""Describe a city."""
msg = city.title() + " is in " + country.title() + "."
print(msg)

describe_city('LONDON')
describe_city('MAZARE QUAID', 'KARACHI')
describe_city('THAR DESERT',"PAKISTAN")

OUTPUT:

4.1 unclear statement!


Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 08

LISTING

OBJECTIVE:

Exploring list/arrays in python programming

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python
programs.
1. Code
Def max_list( list ):
max = l st[ 0 ]
for a i in list:
i a > max:
s max = a
elif
max
print(max_list[1, 2 - 0])
, 8,

Error:

1) “d” is capital in def.

2) For loop syntax is wrong (is should be removed.)

1
Programming Fundamentals (SWE-102) SSUET/QR/114

3) Elif is not correctly indented, secondly elif is used instead of “if”.

4) List can not be define in print, it should be define before and its variables should be written in print

EXAMPLE:
max_list=[1, 2, -8, 0]
print(max_list)

2. Code:
motorcycles = {'honda', 'yamaha', 'suzuki'}
print(motorcycles)
del motorcycles(0)
print(motorcycles)

Error:

Wrong brackets are used to define list. “[ ]” should be use instead of “{ }” in line 1. “[ ]” should be use instead
of “( )” in line 3.

2
Programming Fundamentals (SWE-102) SSUET/QR/114

3.Code
Def dupe_v1(x):
y = []
for i in x:
if i not in y:
y(append(i))
return y

a = [1,2,3,4,3,2,1]
print a
print dupe_v1(a)

Error:

“d” is capital in def.

Conditional statement is not correctly indented in “for loop”.

There is an indentation error in “ y(append(i))” w.r.t “if”.

Print parentheses are not written.

3
Programming Fundamentals (SWE-102) SSUET/QR/114

Whatever is to be printed should be written inside the parenthesis of print.

Wrong syntax. Methods are applied with syntax: y.append(i)

B. What will be the output of the following programs:


1. Code
#Muhammad Maaz
#2020F-BSE-013

list1= [1,2,4,5,6,7,8]
print("Negative Slicing:",list1[-4:-1])
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Odd number:", x[::2])

Output:

4
Programming Fundamentals (SWE-102) SSUET/QR/114

2 Code:
#Muhammad Maaz
#2020F-BSE-013
def multiply_list(elements):
t=1
for x in elements:
t*= x
return t
print(multiply_list([1,2,9]))

OUTPUT:

3 Code
#Muhammad Maaz
#2020F-BSE-013

def add(x,lst=[] ):
if x not in lst:
lst.append(x)
return lst

def main():
list1 = add(2)
print(list1)
list2 = add(3, [11, 12, 13, 14])
print(list2)
main()

Output

5
Programming Fundamentals (SWE-102) SSUET/QR/114

A. Write Python programs for the following:

1. Write a program that store the names of a few of your friends in a list called ‘names’.
Print each person’s name by accessing each element in the list, one at a time.

CODE:
#Muhammad Maaz
2020F-BSE-013

names= [ "\tHasham" , "\tMubashir" , "\tOsaid" ]


print (names[0])
print (names[1])
print (names[2])

OU TPUT:

2. Write a program that make a list that includes at least four people you’d like to invite
to dinner. Then use your list to print a message to each person, inviting them to dinner.
But one of your guest can’t make the dinner, so you need to send out a new set of
invitations. Delete that person on your list, use del statement and add one more person at
the same specified index, use the insert( ) method. Resend the invitation.

CODE:
#Muhammad Maaz
#2020F-BSE-013

#Invitation
guests = ["Hasham", "Osaid" , "Mubashir", "Hassan"]

name = guests[0].title()
print(name + ", please come to dinner.")

name = guests[1].title()
print(name + ", please come to dinner.")

6
Programming Fundamentals (SWE-102) SSUET/QR/114

name = guests[2].title()
print(name + ", please come to dinner.")

name = guests[3].title()
print(name + ", please come to dinner.\n")

print("Since Osaid can’t make the dinner so;\n")


"""guest can't come using del statement to remove and insert function to add other"""
del guests[1]
guests.insert(1, "Usman")

print("\tNEW INVITATION")
name = guests[0].title()
print(name + ", please come to dinner.")

name = guests[1].title()
print(name + ", please come to dinner.")

name = guests[2].title()
print(name + ", please come to dinner.")

name = guests[3].title()
print(name + ", please come to dinner.")

OUTPUT:

7
Programming Fundamentals (SWE-102) SSUET/QR/114

3. Write a program that take list = [30, 1, 2, 1, 0], what is the list after applying each of the
following statements? Assume that each line of code is independent.
• list.append(40)
• list.remove(1)
• list.pop(1)
• list.pop()
• list.sort()
• list.reverse()

CODE:
#Muhammad Maaz
#2020F-BSE-013

print("\tPYTHON FUNCTIONS")

#taking list
list = [30, 1, 2, 1, 0]
print("\tLIST", list)

#using append function for adding element


list.append(40)
print(" \tUSING 'APPEND' FUNCTION:",list)

#using remove function for removing element


list.remove(1)
print(" \tUSING 'REMOVE' FUNCTION:",list)

#using list.pop to remove the element at specified position


list.pop(1)
print(" \tUSING 'POP(1)' FUNCTION:",list)
list.pop()
print(" \tUSING 'POP()' FUNCTION:",list)

'''usnig sort function for sorting element


This method sorts the list ascending by default.'''
list.sort()
print(" \tUSING 'SORT' FUNCTION:",list)

'''using reverse function reversing element


This method reverse the list decending by default'''
list.reverse()
print(" \tUSING 'REVERSE' FUNCTION:",list)

OUTPUT:
8
Programming Fundamentals (SWE-102) SSUET/QR/114

4. Write a program to define a function called ‘printsquare’ with no parameter, take first 7
integer values and compute their square and stored all square values in the list.

CODE:
#Muhammad Maaz
#2020F-BSE-013

print("SQUQRE OF 1st 7 INTEGERS")


def printsquare():
m = list()
for i in range(1,8):
m.append(i**2)
print(m)

printsquare()

OUTPUT:

9
Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 09
SEARCHING & SORTING

OBJECTIVE
Searching and sorting data in the form of list.
EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python
programs.
1. Code
'apple' is in ['orange', 'apple', 'grape']

Output
“is” it a predefined keyword in python and you can’t use it like that. “is” it used
to see if two objects have same memory address. And the list function is not
used.

2. Code
def countX(lst, x):
return lst.count(x)

Output:

The interpreter does not throw an error because you only define the function.

10
Programming Fundamentals (SWE-102) SSUET/QR/114

What will be the output of the following programs:

1. Code

#Muhammad Maaz
#2020F-BSE-013

strs = ['aa', 'BB', 'zz', 'CC']


print (sorted(strs))
print (sorted(strs, reverse=True))

Output

2 Code

#Muhammad Maaz
#2020F-BSE-013

test_list = [1, 4, 5, 8, 10]


print ("Original list : " , test_list)

# check sorted list

if(test_list == sorted(test_list)):
print ("Yes, List is sorted.")
else :
print ("No, List is not sorted.")

11
Programming Fundamentals (SWE-102) SSUET/QR/114

Output

C. Write Python programs for the following:

1. Write a program that take function which implements linear search. It should take a
list and an element as a parameter, and return the position of the element in the list. The
algorithm consists of iterating over a list and returning the index of the first occurrence
of an item once it is found. If the element is not in the list, the function should return ‘not
found’ message.

Code:

#Muhammad Maaz
#2020F-BSE-013

def maaz(brr,z):
for i in range(len(brr)):
if brr[i] == z:
return i
return -1
brr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
z=9
print("Element found at index:" + str(maaz(brr,z)))

12
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

2. Write a program that create function that takes two lists and returns True if they have
at least one common member. Call the function with at least two data set for searching.

Code:
#Muhammad Maaz
#2020F-BSE-013

def data(list1, list2):


result = False
for m in list1:
for z in list2:
if m == z:
result = True
return result
print(data([1,2,3,4,5], [5,6,7,8,9]))
print(data([1,2,3,4,5], [6,7,8,9]))

Output:

13
Programming Fundamentals (SWE-102) SSUET/QR/114

3. Write a program that create function that merges two sorted lists and call two list
with random numbers.
Code:
#Muhammad Maaz
#2020F-B SE-013

def maaz(l1=[],l2=[]):
check = l1+l2
return sorted(check)
print(maaz([1,5,4],[0,3,9]))
print(maaz([1,5654,4],[0,3,1,5,13246546546514654654,1,9]))

Output:

14
Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 10

TUPLE AND DICTIONARY

EXERCISE

A. Point out the errors, if any, in the following Python programs.


1. Code
t = (1, 2, 3)
t.append(4)
t.remove(0)
del tup[0]

Output

Error in this program in the second line of append because tuple dictionary does not have
proper attribute so the program causing error.

2. Code
1user_0=['username':'efermi','first':'enrico','last':'fermi',]
for key, value in 1user_0.items():
print("\nKey: " ,key)
print("Value: " ,value)

Output:

The First line contains an error in this program because 0 can be written as an index. And
the index can not be specified correctly, which causes program errors.

15
Programming Fundamentals (SWE-102) SSUET/QR/114

What will be the output of the following programs:


1. Code
#Muhammad Maaz
#2020F-BSE-013
tuple1 = ("green", "red", "blue")
tuple2 = tuple([7, 1, 2, 23, 4, 5])
tuple3 = tuple1 + tuple2
print(tuple3)
tuple3 = 2 * tuple1
print(tuple3)
print(tuple2[2 : 4])
print(tuple1[-1])

Output

2Code
#Muhammad Maaz
#2020F-BSE-013
def main():
d = {"red":4, "blue":1, "green":14, "yellow":2}
print(d["red"])
print(list(d.keys()))
print(list(d.values()))
print("blue" in d)
print("purple" in d)
d["blue"] += 10
print(d["blue"])
main() # Call the main function

Output

16
Programming Fundamentals (SWE-102) SSUET/QR/114

C. Write Python programs for the following:

1. Write a program that create a buffet-style restaurant offers only five basic foods.
Think of five simple foods, and store them in a tuple. (Hint:Use a for loop to print each
food the restaurant offers. Also the restaurant changes its menu, replacing two of the
items with different foods and display the menu again.

Code

#Muhammad Maaz
#2020F-BSE-013

print("\t\t ")
print("\t\t===>** ' A BUFFET STYLE RESTAURANT '** <===")
print("\t\t ")
menu_card = (
' \tSandwich', ' \tNuggets', ' \tPizza',
' \tBurger', ' \tCakes',
)

print("\t\tYOU CAN ORDER FROM THE FOLLOWING MENU ITEMS:" )


for card in menu_card:
print("\t*"+card)

menu_change = (
' \tClub sandwich', ' \tChicken Karhai', ' \tBiryani',
' \tNehari', ' \tPizza',
)
print("\t\t ")
print("\n\t\t\t--->OUR MENU HAS BEEN UPDATED<---")
print("\t\t ")
print("\t\tYOU CAN ORDER NOW FROM THE FOLLOWING NEW MENU
ITEMS:")
for card in menu_change:
print("\t*"+card)
print("\t\t ")

17
Programming Fundamentals (SWE-102) SSUET/QR/114

Output

2 Write a program for “Guess the capitals” using a dictionary to store the pairs of states and
capitals so that the questions are randomly displayed. The program should keep a count of
the number of correct and incorrect responses.

18
Programming Fundamentals (SWE-102) SSUET/QR/114

Code
#Muhammad Maaz

#2020F-BSE-013

correct = 0

incorrect = 0

m= int(input(" How many times you want to run : "))

dictionary = dict ({ 'Pakistan' : 'Islamabad' , ' Turkey' : 'Ankara' , 'China' : 'Beijing' ,


'Australia' : 'Canberra'})

for i in range (m):

temp = input (" Enter the state to Display Capital : ")

print (dictionary [temp])

if (dictionary [temp] == dictionary):

correct = correct + 1

else:

incorrect = incorrect + 1

print(" Correct " , str (correct))

print(" Incorrect " , str (incorrect))

Output:

19
Programming Fundamentals (SWE-102) SSUET/QR/114

3 Write a pogram that make a dictionary called favorite_places. Think of three names to use as
keys in the dictionary, and store three favorite places for each person through list. Loop through
the dictionary, and print each person’s name and their favorite places.
Output look alike:
abc likes the following places:
- Bear Mountain
- Death Valley
- Tierra Del Fuego

Code
#Muhammad Maaz
#2020F-BSE-013

print("\n\t\t ==>FAVOURITE PLACES FOR EACH PERSON<== ")


liking_places= {"\t\tHASHAM":["YARKHUN VALLEY", "HINGOL NATIONAL PARK",
"SWAT"],"\t\tMUBASHIR":["BADSHAHI MOSQUE", "MINAR-E-PAKISTAN",
"WAGAH BORDER"]
,"\t\tOSAID":["BADSHAHI MOSQUE", "DAMAN-E-KOH", "HUNZA
VALLEY"]}

for name, places in liking_places.items():


print(name.title() + " LIKES THE FOLLOWING PLACES:")

for place in places:


print("\t*" + place.title())

Output:

20
Programming Fundamentals (SWE-102) SSUET/QR/114

LAB#11
MODULES AND PACKAGES

OBJECTIVE:
Getting familiar with the envoirnment for using modules and packages.

EXERCISE
A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code:
import sys as s
print(sys.executable)
print(sys.getwindowsversion())

Error:

Error in second line in this program because sys function is not used for printing
The sys statement cannot be defined in this program, so the program generates the error.

2. Code:
# import sys as s
# print(sys.executable)
# print(sys.getwindowsversion())

import datetime
from datetime import date
import times
# Returns the number of seconds
print(time.time())
# Converts a number of seconds to a date object
print(datetime.datetime.now())

21
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

The error in this program is in the third line of the program, because the import times
Python is not a module or a function in library, so the program creates an error.

3.Code:
From math import math
# using square root(sqrt) function contained
print(Math.sqrt(25) )
print(Math.pi)
# 2 radians = 114.59 degreees
print(Math.degrees(2))

The error in this program in the first line of the program because import math function not
written in the proper way that’s why program generate the error.

B. What would be the output of the following programs:


1.Code:
#Muhammad Maaz
#2020F-BSE-013

import calendar
yy = 2017
mm = 11
# display the calendar
print(calendar.month(yy, mm))

22
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

2.Code:
#Muhammad Maaz
#2020F-BSE-013

import sys
print(sys.argv)
for i in range(len(sys.argv)):
if i==0:
print("The function is",sys.argv[0])
else:
print("Argument:",sys.argv[i])

Output:

3.Code:
#Muhammad Maaz
#2020F-BSE-013

import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)
# Printing shape of array
print("Shape of array: ", arr.shape)
# Printing size (total number of elements) of array

23
Programming Fundamentals (SWE-102) SSUET/QR/114

print("Size of array: ", arr.size)

Output:

C. Write Python programs for the following:

1. Write a NumPy program to create an 1D array of 10 zeros, 10 ones, 10 fives


Code:
#Muhammad Maaz
#2020F-BSE-013

#using the function of import numpy


import numpy as np
print("\t===>numpy program<===".upper( ) )
array_1=np.zeros(10)
print("\tAn array of 10 zeros:".upper( ))
#print array of 10 zeros
print(array_1)
array_2=np.ones(10)
print("\tAn array of 10 ones:".upper( ))
#print array of 10 ones
print(array_2)
array_3=np.ones(10)*5
print("\tAn array of 10 fives:".upper( ))
#print array of 10 fives
print(array_3)

Output:

24
Programming Fundamentals (SWE-102) SSUET/QR/114

2. Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.

Code:
#Muhammad Maaz
#2020F-BSE-013

#using the function of import numpy


import numpy as np
#using the np arrange the value and the using matrices 3x3
m = np.arange(2, 11).reshape(3,3)
print(m)
print("the program of ranging values from 2 to 10 by '3x3'".capitalize( ) )

Output:

25
Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 12

STRINGS

OBJECTIVE
Working on the strings formatting.

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python programs.

1. Code:

a = "PYTHON"
a[0] = "x"
#Apply Exception for mention error

Error:

The second line of the program has an error in this program due to the incorrect use
of x. The program causes errors that can be applied online.

2. Code:
a = STRING
i = 0
while i < len(b):
c = a[i]

26
Programming Fundamentals (SWE-102) SSUET/QR/114

print(c)
i+=i + 1

Error:

The first line of the program in this program is incorrect, because the line "a" The
program creates an error because you are using an assigned and invalid string syntax.

3. Code:

Def 1my_function(x):
return x[::-1]

mytxt = 1my_function("I wonder how this text looks like backwards")


print(mytxt)

Error:

This is an error in the first line of the program, because def can write uppercase letters. That’s
why does the program create errors.

27
Programming Fundamentals (SWE-102) SSUET/QR/114

B. What would be the output of the following programs:

1. Code:
#Muhammad Maaz
#2020F-BSE-013

s= "Welcome"
for i in range(0, len(s), 2):
print(s[i], end = '')

Output:

2. Code:
#Muhammad Maaz
#2020F-BSE-013

s = input("Enter a string: ")


if "Python" in s:
print("Python", "is in", s)
else:
print("Python", "is not in", s)

Output:

3. Code:
#Muhammad Maaz
#2020F-BSE-013
str='cold'

28
Programming Fundamentals (SWE-102) SSUET/QR/114

list_enumerate=list(enumerate(str))
print("list enumerate:", list_enumerate)
print("list length:", len(str))
s1 = "Welcome to Python"
s2 = s1.replace("o","abc")
print(s2)
a = "Python" + "String"
b = "<" + a*3 + ">"
print(b)

Output:

C. Write Python programs for the following:

Write a program that Store a person’s name, and include some whitespace characters at the
beginning and end of the name. Make sure you use each character combination, "\t" and "\n",
at least once. Print the name once, so the whitespace around the name is displayed. Then
print the name using each of the three stripping functions, lstrip(),rstrip(), and strip().

Code:
#Muhammad Maaz
#2020F-BSE-013

# using Lstrip to remove left side whitespaces


pn = "\t \t --->'MUHAMMAD MAAZ'<---"
print(pn)
print(pn.lstrip())
# using Rstrip to remove right side whitespaces
pn2 ="\n --->'HASHAM BAIG'<--- "
print(pn2)
print(pn2.rstrip())

29
Programming Fundamentals (SWE-102) SSUET/QR/114

# using strip whic removes both Left and right whitespaces


pn3 = "\n\t\t --->'MUBASHIR REHMAN'<--- "
print(pn3)
print(pn3.strip())

Output:

1. Write a program that asks the user for their favourite color. Create the following output
(assuming blue is the chosen color) (hint: use ‘+’ and ‘*’)
blueblueblueblueblueblueblueblueblueblue
blue blue
blueblueblueblueblueblueblueblueblueblue

30
Programming Fundamentals (SWE-102) SSUET/QR/114

Code:
#Muhammad Maaz
#2020F-BSE-013
fc = input("\t\t--->'enter your favourite colour: ".upper())
print()
int= "fc" + "fc"
int1 = fc*10
print("\t\t",int1)
print("\t\t",fc,"\t\t\t\t ", fc)
int2 = fc*10
print("\t\t",int2)

OUTPUT:

31
Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 13

FILE
PROCESSING

OBJECTIVE:

To explore methods to access, open/close, modes contained in external files.

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python
programs.
1. Code
file=open('python.txt','r')
print("using read() mode character wise:")
s1=file.read(19)
print(s1)

Error:

In this there is no error but the first we have to make file name as python and write something
which the code can execute and read 19 value as s1

2. Code:
f1=open("jj",)
f1.write("something")

32
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

In this code file “jj” is not define as text file we have to write as “jj.txt” and write “w”
key to write something

B. Creat a text file named python, Write the following code. Execute it and show the
output. (You can use the Snipping Tool to take a snapshot of your txt.file).
1.Code:
#Muhammad Maaz
#2020F-BSE-013

def main():
# Open file for output
outfile=open('D:\\python.txt','w')
# Write data to the file
outfile.write("Bill Clinton\n")
outfile.write("George Bush\n")
outfile.write("Barack Obama")
print(outfile)
# Close the output file
outfile.close()
main()

Output:

33
Programming Fundamentals (SWE-102) SSUET/QR/114

2.Code:
#Muhammad Maaz
#2020F-BSE-013

def main():
# Open file for output
outfile=open('python.txt','x')
# Write data to the file
outfile.write("var, account_balance, client_name")
outfile.write("var = 1\n account_balance1000.0\nclient_name = 'John Doe'")
print(outfile)
# Close the output file outfile.close()
main()

Output:

C. Write Python programs for the following:

1. Write a program that create a function called “file_read”, to read an entire text file

Code:
#Muhammad Maaz
#2020F-BSE-013
print(" task".upper())
file_read = open ('try.txt', 'r')
for i in file_read:
print(i)

34
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

2 Write a program that reads the content and replace any word in a string with
different word.
Example:
Replace ‘dog’ with ‘cat’in a sentence

Code:
#Muhammad Maaz
#2020F-BSE-013

filename = 'rat.txt'

with open(filename) as f:
lines = f.readlines()

for line in lines:


print(line.rstrip().replace('dog', 'dog'))

Output:

35
Programming Fundamentals (SWE-102) SSUET/QR/114

3. Write a program that prompts the user for their name. When they respond,
write their name to a file called guest.txt.
Code:
#Muhammad Maaz
#2020F-BSE013

maaz = 'guest.txt'

print("Enter 'quit' when you are finished.")


while True:
name = input("\nWhat's your name? ")
if name == 'quit':
break
else:
with open(maaz, 'a') as mz:
mz.write(name + "\n")
print("Assalamo Aluikum " + name + ", Welcome you've been added to the guest
list.")

Output:

36

You might also like