Py (1) Procedure 2024
Py (1) Procedure 2024
PROCEDURE
Result: Installed and set up the environment & run Python and Used Command Line and IDE to
create and execute a python program
Aim: to Write and test a python program to demonstrate print statement, comments, different
types of variables.
Tools/Equipments/Instruments: A working PC ,Python 3.11 application
PROCEDURE
Step 1 : Start python IDLE shell and click on file menu and select new file
Step 2: Type the below code in the opened window .
Step 3: save it. Select run module from run menu
#Program 1
A=10
B=20
C=a+b
Print(“the sum”,c)
#Print statement
# Python 3.x program showing
# how to print data on
# a screen
x=5
# Two objects are passed
print("x =", x)
#commenting
#print("Hello, World!")
print("Cheers, Mate!")
#multiline
#This is a comment
#written in
#more than just one line
print("Hello, World!")
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
x = str("Hello World")
print(x)
x = int(20)
print(x)
x = float(20.5)
print(x)
x = complex(1j)
print(x)
x = range(6)
print(x)
x = dict(name="John", age=36)
print(x)
x = bool(5)
print(x)
x = bytes(5)
print(x)
x = bytearray(5)
print(x)
x = memoryview(bytes(5))
print(x)
x=none
print(x)
Result: Wrote and tested python program to demonstrate print statement, comments, different
types of variables.
Aim: to Write and test a python program to perform data and data type operations, string
operations, date, input and output, output formatting and operators.
Tools/Equipments/Instruments: A working PC ,Python 3.11 application
PROCEDURE
String operations
# Python Program for Creation of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
print(x.year)
print(x.strftime("%A"))
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
output formatting
Arithmatic operators
# Examples of Arithmetic Operator
a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(mod)
print(p)
comparison operators
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
logical operators
# Print a or b is True
print(a or b)
bitwise operators
assignment operators
# Assign value
b=a
print(b)
Result: successfully performed data and data type operations, string operations, date, input and
output, output formatting and operators
PROCEDURE
operator precedence
# Examples of Operator Precedence
operator associativity
# Examples of Operator Associativity
# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)
# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
print(5 - (2 + 3))
# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)
PROCEDURE
if statement
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
if else
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
whether palindrome
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
nested if
# python program to illustrate nested If statement
#!/usr/bin/python
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")
if else if else
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
# Python program to find the largest number among the three input numbers
Result: successfully Construct and analyzed code segments that use branching statements.
PROCEDURE
sum of n numbers
factorial = 1
num = 29
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
sum = 0
i=1
while i<=n:
sum = sum+i
i = i+1
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
counter = 0
for j in range(i+1):
print(j+1, end=" ")
print("\n")
i=i+1
Result: successfully Construct and analyzed code segments that perform iteration.
PROCEDURE
'''
I am a
multi-line comment!
'''
print("Hello World")
#docstring
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
# Multi-line Docstrings
def my_function(arg1):
"""
Summary line.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print(my_function.__doc__)
Returns:
binary_sum (str): Binary string of the sum of a and b
'''
binary_sum = bin(a+b)[2:]
return binary_sum
print(add_binary.__doc__)
...
Attributes
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
Methods
-------
info(additional=""):
Prints the person's name and age.
"""
Parameters
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
"""
self.name = name
self.surname = surname
self.age = age
If the argument 'additional' is passed, then it is appended after the main info.
Parameters
----------
additional : str, optional
More info to be displayed (default is None)
Returns
-------
None
"""
Result: successfully Documented code segments using comments and documentation strings
13 Write programs using Python language.
13.4 Document and Structure Code
13.4.2 Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple
Aim: to Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple
PROCEDURE
b1=[0,1,2]
Result: successfully Construct and analyzed code segments that include List
comprehensions,Construct and analyze code segments that include tuple
Aim: to Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple
PROCEDURE
Result: successfully Construct and analyzed code segments that include Dictionary
comprehensions
PROCEDURE
return result
Save as fibo.py
import fibo
fibo.fib(5)
PROCEDURE
#Write a Python program to generate a random color hex, a random alphabetical string, random
value between two integers (inclusive) and a random multiple of 7 between 0 and 70.
import random
import string
print("Generate a random color hex:")
print("#{:06x}".format(random.randint(0, 0xFFFFFF)))
print("\nGenerate a random alphabetical string:")
max_length = 255
s = ""
for i in range(random.randint(1, max_length)):
s += random.choice(string.ascii_letters)
print(s)
print("Generate a random value between two integers, inclusive:")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print("Generate a random multiple of 7 between 0 and 70:")
print(random.randint(0, 10) * 7)
#Python Program to find the area of a triangle given all three sides
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
if a == 0:
print("Invalid")
return -1
d=b*b-4*a*c
sqrt_val = math.sqrt(abs(d))
if d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else: # d<0
print("Roots are complex")
print(- b / (2*a), " + i", sqrt_val)
print(- b / (2*a), " - i", sqrt_val)
# turning 90 degrees
# to the right
rt(90)
#Write a Python program to generate a random integer between 0 and 6 - excluding 6, random
integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and
random date between two dates.
import random
import datetime
print("Generate a random integer between 0 and 6:")
print(random.randrange(5))
print("Generate random integer between 5 and 10, excluding 10:")
print(random.randrange(start=5, stop=10))
print("Generate random integer between 0 and 10, with a step of 3:")
print(random.randrange(start=0, stop=10, step=3))
print("\nRandom date between two dates:")
start_dt = datetime.date(2019, 2, 1)
end_dt = datetime.date(2019, 3, 1)
time_between_dates = end_dt - start_dt
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_dt + datetime.timedelta(days=random_number_of_days)
print(random_date)