#PYTHON(DAY37)
Example Programs
1) Python Program to Find the Sum of Natural Numbers
# Sum of natural numbers up to num
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)
And the output is:
The sum is 136
2) Python Program to Display Powers of 2 Using Anonymous Function
# Display the powers of 2 using anonymous function
terms = 10
# Uncomment code below to take input from the user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
print("The total terms are:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
And the output is:
The total terms are: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512
3) Python Program to Find Numbers Divisible by Another Number
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
And the output is:
Numbers divisible by 13 are [65, 39, 221]
4) Python Program to Convert Decimal to Binary, Octal and Hexadecimal
# Python program to convert decimal into other number systems
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
And the output is:
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
No comments:
Post a Comment