0% found this document useful (0 votes)
28 views

Lab Practice 1

This document contains examples and exercises for learning the fundamentals of computer science and programming in Python. It covers basic expressions, conditionals, iterations, functions, strings, files, exceptions, lists, tuples, dictionaries, sets, and NumPy arrays.

Uploaded by

akalewoldkaleab
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)
28 views

Lab Practice 1

This document contains examples and exercises for learning the fundamentals of computer science and programming in Python. It covers basic expressions, conditionals, iterations, functions, strings, files, exceptions, lists, tuples, dictionaries, sets, and NumPy arrays.

Uploaded by

akalewoldkaleab
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/ 13

Addis Ababa institute of Technology School of Information Technology and Engineering

Fundamentals of computer science and programming

Lab1

Part 1

Using the interpreter, type in the expressions below. Copy and paste the output into the output column. If the result is
unexpected, note that in the third column.

Section 1
Input Output Did it do something
unexpected?
a 5 + 2 * 2
x = 7
y = 3
x + y
total = x + y
total
b 2/3
2.0 * 1.5
(2 + 3) * 10
5.0 // 2
5.0 % 2
9 ** (1 / 2)
-13 // 4
7.5 % 3.5

c a
'a + b'
'a' + 'b'
'a' * 'b'
'a' * 2

d print('Welcome to Python!')
print("Welcome to Python!")
print('Welcome', 'to', 'Python!')
print('Welcome\nto\n\nPython!')
print('Display "hi" in quotes')
print('Display 'hi' in quotes')
print('Display \'hi\' in quotes')
print("Display the name O'Brien")
print("Display \"hi\" in quotes")
print("""Display "hi" and 'bye' in quotes""")
e triple_quoted_string = """This is a
triple-quoted string that spans two lines"""
print(triple_quoted_string)
triple_quoted_string
name = input("What's your name? ")
name

f value1 = input('Enter first number: ')


value2 = input('Enter second number: ')
value1 + value2
int(value1) + int(value2)
type(7)
type(4.1)
type('dog')

Section 2 (conditionals)
Input Output Did it do something
unexpected?

a x = 2
y = 3
if x > y:
print('x is greater')
elif x < y:
print('y is greater')
else:
print('x & y are equal')
b x = int(input('Enter a number'))

if x % 2 == 0:
print('even')
else:
print('odd')

Section 3 (iterations)

Input Output Did it do something


unexpected?

a x = 10
while x > 0:
print(x)
x -=1

for x in range(0, 11,2):


print(x)
b for x in range(0, 11,2):
if x == 6:
continue
print(x)

for x in range(0, 11,2):


if x == 6:
break for x in range(0, 11,2):
print(x)
print(x)

for x in range(1, 10):


for y in range(x):
print('*', end='')
print()
Section 4 (functions)
Input Output Did it do something
unexpected?

a grade = int(input('Enter grades, when you


finish enter -1\t'))
sum = 0
counter = 0
while grade != -1:
sum = sum + grade
counter = counter + 1
grade = int(input('Enter grades, when
you finish enter -1\t'))
average = sum / counter

print('the average grade is ',average)

b def square_root(number):
return number ** (0.5)

square_root(4)
square_root(2)
Section 5 (strings)

Input Output Did it do something


unexpected?

a f'{65:c}'
f'{17.489:.2f}'
f'{15:b}'
f'{15:x}'
f'{15:o}'
f'{"hello":s} {7}'

b f'[{27:10d}]'
f'[{3.5:10f}]'
f'[{"hello":10}]'
f'[{27:<15d}]'
f'[{"hello":>15}]'
f'[{3.5:^7.1f}]'

c f'[{27:+10d}]'
f'[{27:+010d}]'
print(f'{27:d}\n{27: d}\n{-27: d}')
f'{12345678:,d}'
f'{123456.78:,.2f}'
'{} {}'.format('Amanda', 'Cyan')
'{0} {0} {1}'.format('Happy', 'Birthday')
d sentence = ' This is a test string. '
sentence.strip()
'happy birthday'.capitalize()
'happy birthday'.title()
'Orange' < 'orange'
'Orange' == 'orange'

e sentence = 'to be or not to be that is the


question'
sentence.count('to')
sentence.index('not')
'that' in sentence

Section 6 (files and exceptions)

Input Output Did it do


something
unexpected?

a with open('accounts.txt', mode='w') as accounts:


accounts.write('100 Jones 24.98\n')
accounts.write('200 Doe 345.67\n')
print('100 Jones 24.98', file=accounts)
with open('accounts.txt', mode='r') as accounts:
print(f'{"Account":<10}{"Name":<10}{"Balance":>10}')
for record in accounts:
account, name, balance = record.split()
print(f'{account:<10}{name:<10}{balance:>10}')

b while True:
# attempt to convert and divide values
try:
number1 = int(input('Enter numerator: '))
number2 = int(input('Enter denominator: '))
result = number1 / number2
except ValueError:
print('You must enter two integers\n')
except ZeroDivisionError:
print('Attempted to divide by zero\n')
else:
print(f'{number1:.3f} / {number2:.3f} = {result:.3f}')
break
Section 7 (lists and tuples)

Input Output Did it do something


unexpected?

a c = [-45, 6, 0, 72, 1543]


c
len(c)
c[4]
c[4] = 17
c[-1]
s = 'hello'
s[1]
s[0] = 'H'

b another_student_tuple = ('Mary', 'Red', 3.3)


another_student_tuple
student_tuple = 'John', 'Green', 3.3
student_tuple
student_tuple[0] = 'test'

c student_tuple = ('Amanda', 'Blue', [98, 75, 87])


student_tuple[2][1] = 85
student_tuple
student_tuple = ('Amanda', [98, 85, 87])
first_name, grades = student_tuple
first_name
grades

colors = ['red', 'orange', 'yellow']


list(enumerate(colors))

for index, value in enumerate(colors):


print(f'{index}: {value}')

d numbers = [2, 3, 5, 7, 11, 13, 17, 19]


numbers[2:6]
numbers[:4]
numbers[6:]
numbers[:]
numbers[1:5:2]
numbers[::-1]
numbers[0:3] = ['two', 'three', 'five']
numbers

e color_names = ['orange', 'yellow', 'green']


color_names.insert(0, 'red')
color_names.append('blue')
color_names
Section 8 (Arrays, dictionaries, and sets)

Input Output Did it do


something
unexpected?

a days_per_month = {'January': 31, 'February': 28, 'March': 31}


days_per_month
for month, days in days_per_month.items():
print(f'{month} has {days} days')

roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X':


100}
roman_numerals['V']
roman_numerals['X'] = 10
roman_numerals

b colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'}


colors
{1, 3, 5} | {2, 3, 4}
{1, 3, 5} & {2, 3, 4}
{2,3} < {2, 3, 4}

c import numpy as np
numbers = np.array([1, 4, 9, 16, 25, 36])
np.sqrt(numbers)
numbers2 = np.arange(1, 7) * 10
numbers2
np.add(numbers, numbers2)
np.multiply(numbers2, 5)
numbers3 = numbers2.reshape(2, 3)
numbers3

numbers4 = np.array([2, 4, 6])


np.multiply(numbers3, numbers4)
grades = np.array([[87, 96, 70], [100, 87, 90]])
grades
grades[1][1]
grades.T

You might also like