2020f Bse 013 P Fund Lab File
2020f Bse 013 P Fund Lab File
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.
9 15-12-20
12 22-12-20
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
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
2. 1TEXT = "SSUET"
NUMBER = 1
print(NUMBER+ TEXT)
1TEXT = "SSUET"
^
Syntax Error: invalid syntax
3. a = b = 3 = 4
a = b = 3 = 4
^
Syntax Error: can’t assign to literal
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:
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.
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
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.
1. a=5
print("a =", a, sep='0', end=',')
Code:
#Muhammad Maaz
#2020F-BSE-013
a=5
print("a =", a, sep='0', end=',')
OUTPUT:
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:
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
This code is causing error because variable b& c are not defined.
2. Code
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.
#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:
CODE:
#Muhammad Maaz
#2020F-BSE-013
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
OUTPUT:
LAB # 05
OBJECTIVE
EXERCISE
A. Point out the errors, if any, in the following Python programs.
1. Code:
for(;;)
{
printf("SSUET")
}
2. Code:
count = 4
while n < 8
count = count + 3:
print(count)
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
OUTPUT:
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
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
OUTPUT:
OBJECTIVE
Working on nested statements and control loop iteration using break and continue.
EXERCISE
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.
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
OUTPUT:
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
FUNCTIONS
OBJECTIVE
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.
OUTPUT:
2. CODE:
#Muhammad Maaz
#2020F-BSE-013
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:
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:
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:
LAB # 08
LISTING
OBJECTIVE:
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
Programming Fundamentals (SWE-102) SSUET/QR/114
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:
3
Programming Fundamentals (SWE-102) SSUET/QR/114
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
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
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("\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)
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
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
1. Code
#Muhammad Maaz
#2020F-BSE-013
Output
2 Code
#Muhammad Maaz
#2020F-BSE-013
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
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
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
EXERCISE
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
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
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',
)
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
correct = correct + 1
else:
incorrect = incorrect + 1
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
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.
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
Output:
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
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]
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
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
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:
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
29
Programming Fundamentals (SWE-102) SSUET/QR/114
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:
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:
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()
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'
Output:
36