Lab 1-Part 1
Opening IDLE
Go to the start menu, find Python, and run the program labeled 'IDLE' (Stands for Integrated
Development Environment)
Code Example 1 - Hello, World!
>>> print ("Hello, World!")
Lab 1-Part 2
Math in Python
Calculations are simple with Python, and expression syntax is straightforward: the operators +,
-, * and / work as expected; parentheses () can be used for grouping.
# Python 3: Simple arithmetic
>>> 4/9
0.4444444444444444
>>> 3 ** 7 #Exponent operator
2187
>>> 15/3 #classic division returns a float
5.0
>>> 15//2 #floor division
>>> 23%3 #Modulus operator
2
Comments in Python:
#I am a comment. I can say whatever I want!
Variables:
print ("This program is a demo of variables")
v=1
print ("The value of v is now", v)
v=v+1
print ("v now equals itself and by plus one, making its worth", v)
print ("To make v ten times bigger, you would have to type v = v * 10")
v = v * 10
print ("There you go, now v equals", v, "and not", v / 10)
1
OUTPUT:
Strings:
word1 = "Good"
word2 = "Morning"
word3 = "have a nice day!"
print (word1, word2)
sentence = word1 + " " + word2 + " " +word3
print (sentence)
OUTPUT:
Boolean Logic:
Boolean logic is used to make more complicated conditions for if statements that rely on more
than one condition. Python’s Boolean operators are and, or, and not. The and operator takes
two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise
it evaluates to False.
The or operator also takes two arguments. It evaluates if either (or both) of its arguments are
False. Unlike the other operators we’ve seen so far, not only takes one argument and inverts
it. The result of not True is False, and not False is True.
Conditional Statements:
‘if' - Statement
2
x=1
if x == 1:
print ("x still equals 1, I was checking!")
‘if - else' - Statement
a=1
if a > 5:
print ("This shouldn't happen.")
else:
print ("This should happen.")
‘elif' - Statement
z=4
if z > 70:
print ("Something is very wrong")
elif z < 7:
print ("This is normal")
LAB TASK 1
Lab Question:
Open IDLE and run the following program. Try different integer values for separate runs of
the program. Play around with the indentation of the program lines of code and run it again.
See what happens. Make a note of what changes you made and how it made the program
behave. Also, note any errors, as well as the changes you need to make to remove the errors.
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 122
>>> if x < 0:
3
x=0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
Lab 1- Part 3
Input from user:
The input() function prompts for input and returns a string.
4
a = input (“Enter Value for variable a: ”)
print (a)
Indexes of String:
Characters in a string are numbered with indexes starting at 0:
Example:
name = "J. Smith“
Accessing an individual character of a string:
variableName [ index ]
Example:
print (name, " starts with", name[0])
Output:
J. Smith starts with J
Input:
input: Reads a string of text from user input.
Example:
name = input("What's your name? ")
print (name, "... what a nice name!")
Output:
What's your name? Ali
Ali... what a nice name!
String Properties:
len(string) - number of characters in a string (including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Linkin Park"
length = len(name)
5
big_name = str.upper(name)
print (big_name, "has", length, "characters")
Output:
LINKIN PARK has 11 characters
Strings and numbers:
ord(text) - converts a string into a number.
Example: ord(‘a’) is 97, ord("b") is 98, ...
Characters map to numbers using standardized mappings such as ASCII and
Unicode.
chr (number) - converts a number into a string.
Example: chr(99) is "c"
Loops in Python:
The 'while' loop
a=0
while a < 10:
a=a+1
print (a )
Range function:
Range(5) #[0,1,2,3,4]
Range(1,5) #[1,2,3,4]
Range(1,10,2) #[1,3,5,7,9]
The 'for' loop
for i in range(1, 5):
print (i )
for i in range(1, 5):
6
print (i)
else:
print ('The for loop is over')
Functions:
How to call a function?
function_name(parameters)
Code Example - Using a function
def greet(): #function definition
print(“Hello”)
print(“Good Morning”)
greet() #function calling
Define a Function?
def function_name(parameter_1,parameter_2):
{this is the code in the function}
return {value (e.g. text or number) to return to the main program}
range() Function:
If you need to iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates iterator containing arithmetic progressions:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It is possible to let the range start at another number, or to specify a different increment
(even negative; sometimes this is called the ‘step’):
>>> list(range(5, 10) )
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3) )
[0, 3, 6, 9]
>>> list(range(-10, -100, -30) )
[-10, -40, -70]
The range() function is especially useful in loops.
7
LAB TASK 2
Lab Question:
Write a simple calculator program. Follow the steps below:
a. Declare and define a function named Menu which displays a list of choices for user
such as addition, subtraction, multiplication, & classic division. It takes the choice from
user as an input and return.
b. Define and declare a separate function for each choice.
c. In the main body of the program call respective function depending on user’s choice.
d. Program should not terminate till user chooses option to “Quit”.
PROGRAM
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
def menu():
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice="0"
while(choice!="Quit"):# Take input from the user
menu()
choice = input("Enter choice(1/2/3/4) or Quit to exit the program:")
if choice!='Quit':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
8
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
9
10
OUTPUT
LAB TASK 3
Lab Question:
Q) Implement the following functions for the calculator you created in the above task.
a. Factorial
b. x_power_y (x raised to the power y)
c. log
d. ln (Natural log)
PROGRAM
import math
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
11
def divide(x, y):
return x / y
# This function is for Factorial
def Fact(x):
factorial = 1
if x < 0:
print("Sorry, factorial does not exist for negative numbers")
elif x == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, x + 1):
factorial = factorial * i
print("The factorial of", x, "is", factorial)
#this is for power
def Powers():
print('Powers: What number would you like to multiply by itself?')
l = float(input('Number:'))
print('Powers: How many times would you like to multiply by itself?')
m = float(input('Number:'))
print('Your Answer is:', l ** m)
def log():
x=float(input("Enter the number:"))
print("The log of",x," is ",math.log(x))
def menu():
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Factorial")
print("6.Power")
print("7.Log")
choice="0"
while(choice!="Quit"):# Take input from the user
menu()
choice = input("Enter choice(1/2/3/4/5/6/7) or Quit to exit the program:")
if choice!='Quit' :
if choice=='1' or choice=='2'or choice=='3' or choice=='4':
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
12
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
if choice == '5':
num = int(input("Enter number: "))
Fact(num)
if choice == '6':
Powers()
if choice=='7':
log()
else:
print("Invalid input")
13
14
OUTPUT
LAB TASK 4
Lab Question:
1. Create a class name basic_calc with following attributes and methods;
Two integers (values are passed with instance creation)
Different methods such as addition, subtraction, division, multiplication
Create another class inherited from basic_calc named s_calc which should have the
following additional methods;
Factorial, x_power_y,log, ln, sin, cos, tan etc
PROGRAM
import math
class basic_calc():
def __init__(self):
pass
def add(self,x, y):
return x + y
15
# This function subtracts two numbers
def subtract(self,x, y):
return x - y
# This function multiplies two numbers
def multiply(self,x, y):
return x * y
# This function divides two numbers
def divide(self,x, y):
return x / y
cal=basic_calc();
# This function is for Factorial
class s_calc(basic_calc):
def Fact(self):
x=int(input("enter no"))
factorial = 1
if x < 0:
print("Sorry, factorial does not exist for negative numbers")
elif x == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, x + 1):
factorial = factorial * i
print("The factorial of", x, "is", factorial)
#this is for power
def Powers(self):
print('Powers: What number would you like to multiply by itself?')
l = float(input('Number:'))
print('Powers: How many times would you like to multiply by itself?')
m = float(input('Number:'))
print('Your Answer is:', l ** m)
def log(self):
x=float(input("Enter the number:"))
print("The log of",x," is ",math.log(x))
def sin(self):
i = int(input('enter number for Sin '))
print("result is:", end="")
print(math.sin(i))
16
def cos(self):
i = int(input('enter number for Cos '))
print("result is:", end="")
print(math.cos(i))
def tan(self):
i = int(input('enter number for tan '))
print("result is:", end="")
print(math.tan(i))
child=s_calc();
a = int(input('enter first number'))
b=int(input('enter second number'))
print("Addition of numbers is:",(cal.add(a,b)))
print("Subtraction Of Number is:",(cal.subtract(a,b)))
print("Multiplication Of Number is:",(cal.multiply(a,b)))
print("Division Of Number is:",(cal.divide(a,b)))
print(child.Fact())
print(child.Powers())
print(child.log())
print(child.sin())
print(child.cos())
print(child.tan())
17
18
19
OUTPUT
LAB TASK 5
Lab Question:
Q) Modify the classes created in the above task under as follows:
Create a module name basic.py having the class name basic_calc with all the attributes and
methods defined before.
Now import the basic.py module in your program and do the inheritance step defined before
i.e. Create another class inherited from basic_calc named s_calc which should have the
following additional methods;
Factorial, x_power_y, log, ln etc
PROGRAM
class basic_calc():
def __init__(self):
pass
def add(self,x, y):
return x + y
# This function subtracts two numbers
def subtract(self,x, y):
return x - y
# This function multiplies two numbers
def multiply(self,x, y):
return x * y
# This function divides two numbers
def divide(self,x, y):
return x / y
class:
20
import basic
cal = basic.basic_calc();
a = int(input('enter first number'))
b=int(input('enter second number'))
print("Addition of numbers is:",(cal.add(a,b)))
print("Subtraction Of Number is:",(cal.subtract(a,b)))
print("Multiplication Of Number is:",(cal.multiply(a,b)))
print("Division Of Number is:",(cal.divide(a,b)))
class s_calc(basic_calc):
def Fact(self):
x=int(input("enter no"))
factorial = 1
if x < 0:
print("Sorry, factorial does not exist for negative numbers")
elif x == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, x + 1):
factorial = factorial * i
print("The factorial of", x, "is", factorial)
#this is for power
def Powers(self):
print('Powers: What number would you like to multiply by itself?')
l = float(input('Number:'))
print('Powers: How many times would you like to multiply by itself?')
m = float(input('Number:'))
print('Your Answer is:', l ** m)
def log(self):
x=float(input("Enter the number:"))
print("The log of",x," is ",math.log(x))
def sin(self):
i = int(input('enter number for Sin '))
print("result is:", end="")
print(math.sin(i))
def cos(self):
i = int(input('enter number for Cos '))
print("result is:", end="")
21
print(math.cos(i))
def tan(self):
i = int(input('enter number for tan '))
print("result is:", end="")
print(math.tan(i))
child=s_calc();
a = int(input('enter first number'))
b=int(input('enter second number'))
print("Addition of numbers is:",(child.add(a,b)))
print("Subtraction Of Number is:",(child.subtract(a,b)))
print("Multiplication Of Number is:",(child.multiply(a,b)))
print("Division Of Number is:",(child.divide(a,b)))
print(child.Fact())
print(child.Powers())
print(child.log())
print(child.sin())
print(child.cos())
print(child.tan())
OUTPUT
22