Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python - Lab2

The document provides a comprehensive guide on Python programming focusing on loops and selection statements. It includes multiple programs demonstrating the use of for loops, while loops, nested loops, and conditional statements (if/elif/else) along with exercises and solutions. Additionally, it covers converting decimal numbers to binary and includes challenge exercises for further practice.

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)
3 views

Python - Lab2

The document provides a comprehensive guide on Python programming focusing on loops and selection statements. It includes multiple programs demonstrating the use of for loops, while loops, nested loops, and conditional statements (if/elif/else) along with exercises and solutions. Additionally, it covers converting decimal numbers to binary and includes challenge exercises for further practice.

Uploaded by

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

O’TECH

COMPUTER AND LANGUAGE


TRAINING CENTER
DEPARTMENT OF SOFTWARE
PYTHON PROGRAMMING
LAB-2
Loops and Selection

MARCH 25, 2023


Program #1 – For loops
Note: A for loop is used for iterating over a sequence.
With a for loop we can execute a set of statements, once for each item in a list.
To loop through a set of code a specified number of times, we can use the range() function.
range (start, stop, step)
If we don’t specify (write) start the default is 0, and the default for step is 1.
Instructions:
❖ Open Notepad or other editor and write the below code inside.
❖ Save the file with .py extension.
❖ Run the file.
for x in range(5):
print("x = ",x)
for y in range(6,11,1):
print("y = ",y)
for z in range(12,20,2):
print("z = ",z)
for i in range(5,1,-1):
print("i = ",i)
Program #2 – Calculating the sum of the first ten positive integers(1-10) using for loop.
Note: First let’s initialize a sum variable with the value of zero.
At each iteration the current value in the loop is added to sum.
The final value of sum is printed to the user.
Instructions:
❖ Open Notepad or other editor and write the below code inside.
❖ Save the file with .py extension.
❖ Run the file.
sum = 0
for number in range(1,11):
sum = sum + number
print(sum)
Program #3 – Nested loops
Note: A nested loop is a loop inside another loop.
The “inner” loop will be executed one time for each iteration of the “outer loop”.
Instructions:
❖ Write and run the code below.
< for x in range(5):
for y in range(5):
print("Hello")
Instructions:
❖ Write and run the code below.
for i in range(6):
for j in range(i):
print('*',end='')
print()
Instructions:
❖ Write and run the code below.
for i in range(6):
for j in range(6-i):
print('*',end='')
print()
Instructions:
❖ Write and run the code below.
for i in range(6):
print((6-i)*' ',end='')
for j in range(2*i-1):
print('*',end='')
print()
Program #4 – Selection (if/elif/else)
Note: An “if statement” is written by using the if keyword.
The elif keyword is pythons way of saying “if the previous conditions were not true, then try
this condition”.
The else keyword catches anything which isn’t caught by the preceding conditions.
Instructions:
❖ The below program accepts a number from user and prints its additive inverse if the number is
negative else it prints the number itself.
❖ Write and run the code below.
value = float(input("Enter a number: "))
if value < 0:
value = -value
print(value)
else:
print(value)
Instructions:
❖ The below program accepts two number from user and prints the largest of the two.
❖ Write and run the code below.
print("Enter two numbers:")
Value1 = float(input("Enter value1> ") )
Value2 = float(input("Enter value2> ") )
if Value1 < Value2:
Max = Value2
else:
Max = Value1
print("Maximum of inputs is: ", Max)
Instructions:
❖ The below program accepts two number from user and rearranges (sorts) them from the smallest to
the largest.
❖ Write and run the code below.
print("Enter two numbers: \n")
value1 = float(input("Enter value1 > "))
value2 = float(input("Enter value2 > "))
if (value1 > value2):
rememberValue1 = value1
value1 = value2
value2 = rememberValue1
print("The input in sorted order: ",value1,value2)
Program #5 – while loops
Note: With the while loop we can execute a set of statements as long as a condition is true.
bool() produces False for 0 or empty strings.
Instructions:
❖ The code below prints number as long as number is less than 200.
❖ Write the code and run it.
number = 1
while number < 200:
print(number,)
number = number * 2
Program #6 – break, continue and pass in loops
Note: With the break statement we can stop the loop before it has looped through all the items.
With the continue statement we can stop the current iteration of the loop, and continue with
the next.
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Instructions:
❖ A for loop with the break keyword.
❖ Write and run the code below.
x=0
for i in range(5):
if i==3:
break
print("The number is ", i)
Instructions:
❖ A for loop with the continue keyword.
❖ Write and run the code below.
x=0
for i in range(5):
if i==3:
continue
print("The number is ", i)
Instructions:
❖ A for loop with the pass keyword.
❖ Write and run the code below.
for i in range(5):
pass
Instructions:
❖ A while loop with the break keyword.
❖ Write the code and run it.
x = 5
while(x < 10):
x = x + 1
if(x == 8):
break
print(x)
Program #7 – Decimal to binary
Note: To change a decimal to binary, we keep dividing the decimal by two until it’s zero.
The remainders in reverse order are the binary equivalent of the decimal number.
Instructions:
❖ The below code accepts a positive integer from user and converts it into binary.
❖ The code only works for positive integers.
❖ Write the code and execute it.
from math import floor
decimal = int(input("Enter a positive integer: "))
binary = ''
while(decimal > 0):
remainder = str(decimal % 2)
decimal = floor(decimal/2)
binary = remainder + binary
print(binary)
Try The following Exercises:
1. Write a python program to find the given positive integer is odd or even.
2. Write a Python program to print prime number series up to N.
3. Write a python program to find the largest among three numbers.
4. Write a python program to print factorial of a given number
5. Write a program that takes begin and end values and prints out a decimal, binary, octal,
hexadecimal chart like below.
Solution to Exercises:
1. Write a python program to find the given positive integer is odd or even.
Solution:
# Ask the user for a positive integer input.
N = int(input("Enter a positive integer: "))

# Evaluate if N is odd or even


if (N % 2) != 0:
print(N," is an odd number")
else:
print(N," is an even number")

2. Write a Python program to print prime number series up to N.


Solution:
# Ask the user for a positive integer input.
N = int(input("Enter a positive integer: "))

# Loop through each number up to N to check if it’s a prime or composite.


for n in range(2,N):

# Loop from 2 up to the current number.


for i in range(2,n):

# Breaks out of the loop if a factor is found


if (n % i) == 0:
break

# Print the prime number


else:
print(n)

3. Write a python program to find the largest among three numbers.


Solution:
# Ask the user for three numbers.
number1 = float(input("Enter number-1: "))
number2 = float(input("Enter number-2: "))
number3 = float(input("Enter number-3: "))

# Evaluate which number is the largest


if number1 > number2 :
if number1 > number3 :
print("The largest number is: ",number1)
else:
print("The largest number is: ",number3)
else:
if number2 > number3 :
print("The largest number is: ",number2)
else:
print("The largest number is: ",number3)

4. Write a python program to print factorial of a given number.


Solution:
# Ask the user for a positive integer.
number = int(input("Enter a positive integer: "))
# Initialize factorial to 1
factorial = 1

# Update factorial by multiplying each number in the loop


for n in range(1,number + 1):
factorial = factorial * n
print("Factorial of",number,"is",factorial)

5. Write a program that takes begin and end values and prints out a decimal, binary, octal,
hexadecimal.
Solution:
from math import floor
print()
print("SAMPLE OUTPUT")
print("_______________")
print()
start = int(input("Enter begin value: "))
end = int(input("Enter end value: "))
print()
print("DECIMAL"," BINARY"," OCTAL"," HEXA")
print("__________________________________________________")
for decimal in range(start,end+1,1):
binary = ''
octal = ''
hexa = ''
binary_dividened = decimal
octal_dividened = decimal
hexa_dividened = decimal
while(binary_dividened>0):
remainder = str(binary_dividened % 2)
binary = remainder + binary
binary_dividened = floor(binary_dividened/2)
while(octal_dividened>0):
remainder = str(octal_dividened % 8)
octal = remainder + octal
octal_dividened = floor(octal_dividened/8)
while(hexa_dividened>0):
remainder = str(hexa_dividened % 16)
if remainder == '10':
remainder = 'a'
elif remainder == '11':
remainder = 'b'
elif remainder == '12':
remainder = 'c'
elif remainder == '13':
remainder = 'd'
elif remainder == '14':
remainder = 'e'
elif remainder == '15':
remainder = 'f'
hexa = remainder + hexa
hexa_dividened = floor(hexa_dividened/16)
length_decimal = len(str(decimal))
length_binary = len(binary)
length_octal = len(octal)
length_hexa = len(hexa)

indent_decimal = 2 - length_decimal
indent_binary = 8 - length_binary
indent_octal = 2 - length_octal
indent_hexa = 2 - length_hexa

decimal = indent_decimal * ' ' + str(decimal)


binary = indent_binary * '0' + binary
octal = indent_octal * ' ' + octal
hexa = indent_hexa * ' ' + hexa

print(" ",decimal," ",binary," ",octal," ",hexa) print(-b / (2 * a))


Challenge Exercises:
1. Modify exercise number 3 above, so that you can find the largest and the smallest numbers among a
given set of numbers.
2. Modify exercise number 5 above, so that you can find the binary, octal and hexadecimal values of
negative integers.

You might also like