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

Python - Lab

The document outlines a series of Python programming exercises and instructions for beginners, covering topics such as expressions, comments, data types, variables, type conversion, built-in math functions, and user input. Each program includes specific tasks to be executed in the Python IDLE, along with explanations of key concepts and syntax rules. Additionally, the document provides solutions to exercises related to user interaction and mathematical calculations.

Uploaded by

Adonay Yirga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python - Lab

The document outlines a series of Python programming exercises and instructions for beginners, covering topics such as expressions, comments, data types, variables, type conversion, built-in math functions, and user input. Each program includes specific tasks to be executed in the Python IDLE, along with explanations of key concepts and syntax rules. Additionally, the document provides solutions to exercises related to user interaction and mathematical calculations.

Uploaded by

Adonay Yirga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

O’TECH

COMPUTER AND LANGUAGE


TRAINING CENTER
DEPARTMENT OF SOFTWARE
PYTHON PROGRAMMING
LAB-1

MARCH 21, 2023


Program #1 – The Python Interpreter and Expressions
Note: Interpreter executes program in high level languages by translating it one line at a time.
An expression is a combination of values, variables, and operators.
If you type an expression on the Python IDLE, the interpreter evaluates it and displays
the result.
IDLE == Integrated Development and Learning Environment.
Instructions:
❖ Write the following expressions on the Python IDLE.
>>> 3 + 7
10
>>> 3 < 15
True
>>> 'print me'
'print me'
>>> print('print me')
print me
>>> 14 / 3
4.666666666666667
>>> 12 % 3
0
>>> 14 % 3
2
>>> 7.5 / 2
3.75
Program #2 - Comments
Note: Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments start with #, and Python ignores them.
Instructions:
❖ Open Notepad or other editor and write the below code inside.
❖ Save the file with .py extension.
❖ Open the saved file with Python (You can do this from Python IDLE).
#This is a comment
print("Hello, World!")

#This is a comment
#written in
#more than just one line
print("Hello, World!")
Program #3 – Values and Types
Note: A value is one of the fundamental things-like a letter or a number-that a program manipulates.
A value could be a type of an integer, float, Boolean or string.
If you are not sure what type a value has an interpreter could tell you.
You can get data type of an object using type() function.
Values like '2' & "3.5", they look like numbers, but they are in quotation marks like strings.
Instructions:
❖ Write the following expressions on the Python IDLE.
>>> type(2)
<class 'int'>
>>> type(2.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
>>> type("Hello, World!")
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> type("3.5")
<class 'str'>
Program #4 – Variables
Note: A variable is a name that refers to (stores) a value.
A variable is container of a value.
A variable name should start with a letter or underscore (_).
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9 and _).
Variable names are case sensitive (name, Name and NAME are three different variables).
Although it’s legal to use uppercase letters, by convention we don’t.
If you give a variable an illegal name, you get a syntax error.
We use = sign to assign a value to a variable.
Python keywords cannot be used as variable names.
Keywords define the language’s rules and structure. Python has 33 keywords.
and def finally in or while
as del for is pass with
assert elif from import lambda raise yield
break else global None return
class except if nonlocal True
continue False import not try
Instructions:
❖ Write the following expressions on the Python IDLE.
>>> my_name = "Bereket"
>>> _age = 20
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> name = "Selam"
>>> Name
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
Name
NameError: name 'Name' is not defined
>>> 76trombones = "big parade"
SyntaxError: invalid syntax
>>> class = "Programming"
SyntaxError: invalid syntax
Program #5 – Converting between data types
Note: You can change or set data type using int(), str(), bool() or float() functions.
bool() produces False for 0 or empty strings.
Instructions:
❖ Write the following expressions on the Python IDLE.
>>> int("52")
52
>>> float(9)
9.0
>>> bool(1)
True
>>> bool(0)
False
>>> bool("")
False
>>> bool("text")
True
>>> str(52)
'52'
Program #6 – Python built-in math commands (functions)
❖ Write the following expressions on the Python IDLE.
>>> abs(-5)
5
>>> max(20,30,10)
30
>>> min(15,5,20,2)
2
>>> sqrt(4)
2.0
>>> pi
3.141592653589793
>>> e
2.718281828459045

Program #7 – Python program that prompts (asks) the user for his/her amount of money, then
reports how many books with a price of 100 birr the person can afford, and how much more money
he/she will need to afford an additional book.
❖ Open Notepad or other editor and write the below code inside.
❖ Save the file with .py extension.
❖ Open the saved file with Python (You can do this from Python IDLE).
# imports math functions from Python's math module
from math import *

# prompts the user to enter the amount of money he/she has


amount_of_money = input("How much money do you have? \n > ")

# converts string input into an integer


amount_of_money = int(amount_of_money)

# calculates how many books the person could afford with the money
books_affordable = floor(amount_of_money / 100)

# calculates how much money is the person left with after buying books
Remainder = amount_of_money % 100

# calculates how much additional money the person needs to buy one more book
additional_money_needed = 100 - Remainder

# Outputs number of affordable books and additional money needed


print("You can afford ",books_affordable," books")
print("You need an additional ",additional_money_needed," to by one more book")
Try The following Exercises:
1. Ask a user their name and what year they were born then calculate and tell them their age calling
out their name.
2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3
for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60
copies?
3. Modify question #2, so that you ask the user for the number of copies.
4. Evaluate a quadratic equation for a given a, b and c values. (Hint: ax2+bx+c, a 0)
Solution to Exercises:
1. Ask a user their name and what year they were born then calculate and tell them their age by
calling out their name.
Solution:
# Ask the user their name and age and put it in a variable.
name = input("What is your name? \n > ")
birth_year = int(input("What year were you born? \n > "))

# Calculate the age and print it out.


age = 2015 - birth_year
print("Hey",name,"you are",age,"years old.")

2. Suppose the cover price (price on cover) of a book is $24.95, but bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total
wholesale cost for 60 copies?
Solution:
original_price = 24.95
discounted_price = original_price * 0.4
total_copies = 60

books_cost = total_copies * discounted_price


shipping_cost = 3 + (total_copies - 1) * 0.75
total_cost = books_cost + shipping_cost

print(total_cost)

3. Modify question #2, so that you ask the user for the number of copies.
Solution:
original_price = 24.95
discounted_price = original_price * 0.4
total_copies = int(input("How many copies do you want? \n > "))

books_cost = total_copies * discounted_price


shipping_cost = 3 + (total_copies - 1) * 0.75
total_cost = books_cost + shipping_cost

print(total_cost)

4. Evaluate a quadratic equation for a given a, b and c values.


Solution:
import math

a = int(input("a>"))
b = int(input("b>"))
c = int(input("c>"))

# Calculating discriminant using formula


dis = b*b - 4*a*c
sqrt_val = math.sqrt(abs(dis))

# Checking condition for discriminant


if dis > 0:
print("real and different roots")
print((-b + sqrt_val)/(2*a))
print((-b - sqrt_val)/(2*a))
elif dis == 0:
print("real and same roots")
print(-b / (2 * a))
# When discriminant is less than 0
else:
print("Complex roots")
print(-b / (2 * a), " + i", sqrt_val)
print(-b / (2 * a), " - i", sqrt_val)
N.B. There is one problem with above solution. What is it?
Ans: It allows for a to be 0, which could raise ZeroDivisionError.

To solve that, we could either add a condition at the top level or define a function.
if a != 0:
{above conditions}
else:
print("a must be different from zero")
OR
def equationroots(a, b, c)
{above conditions}
if a == 0:
print("a must be different from zero")
else:
equationroots(a, b, c)

You might also like