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

Programs On Loops: A-35 Python Assingment

The document contains a Python assignment submitted by Neha Kangle. It includes 8 programs on loops and 7 programs on functions. The loop programs include calculating Pythagorean triples, printing patterns with stars, finding numbers divisible by 7 and 5, FizzBuzz, validating passwords, displaying the Fibonacci sequence, and counting digits and letters in a string. The function programs include calculating the hypotenuse of a right triangle, a guessing game, printing Pascal's triangle, printing squares, detecting local variables, showing employee details with default parameters, and multiplying two matrices.

Uploaded by

A- 08 Kaushiki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Programs On Loops: A-35 Python Assingment

The document contains a Python assignment submitted by Neha Kangle. It includes 8 programs on loops and 7 programs on functions. The loop programs include calculating Pythagorean triples, printing patterns with stars, finding numbers divisible by 7 and 5, FizzBuzz, validating passwords, displaying the Fibonacci sequence, and counting digits and letters in a string. The function programs include calculating the hypotenuse of a right triangle, a guessing game, printing Pascal's triangle, printing squares, detecting local variables, showing employee details with default parameters, and multiplying two matrices.

Uploaded by

A- 08 Kaushiki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Neha Kangle

A-35

PYTHON ASSINGMENT

Programs on Loops

1. a2 b2 c2.Three numbers, a, b and c, are called a


Pythagorean triple if+=
An example is the triple 3, 4 and 5, since 9 + 16 = 25.
Pythagorean triples can represent, for example, the
length of sides in a right triangle. Write a series of
Python statements that will read three numbers into
variables named a, b and c and then print a message
saying whether or not they are a Pythagorean triple.
Using a for loop, print a table of powers of x, where x
ranges from 1 to 10. For x2,x3.each value x, print the
quantity x,and Using tab characters in your print
statement to make the values line up nicely.
CODE:
def pythagoreanTriplets(limits) :
c, m = 0, 2

# Limiting c would limit


# all a, b and c
while c < limits :

# Now loop on n from 1 to m-1


for n in range(1, m) :
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if c > limits :
break

print(a, b, c)

m=m+1

# Driver Code
if __name__ == '__main__' :

limit = 10
pythagoreanTriplets(limit)

2. Write a program that reads an integer value n from the


user, then produces n lines of output. The first line
contains 1 star, the second 2 stars, and so on until the
last line, which should have n stars. Can you write this
using only a single loop? Hint:
remember what the expression ‘+’*5 does.
Enter a size: 5
+
++
+++
++++
+++++

CODE:
# This is the example of print simple pyramid pattern
n = int(input("Enter the number of rows : "))
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of columns
# values is changing according to outer loop
for j in range(0, i + 1):
# printing stars
print("+ ", end="")

# ending line after each row


print()

3. Write a Python program to find those numbers which


are divisible by 7 and multiple of 5, between 1500 and
2700 (both included).
CODE:
nl=[]
for x in range(1500, 2701):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))
2
for i in range(1500,2701):

if i%7==0 and i%5==0:

print(" ",i)

4. Write a Python program which iterates the integers


from 1 to 50. For multiples of three print "Fizz" instead
of the number and for the multiples of five print
"Buzz". For numbers which are multiples of both three
and five print "FizzBuzz".
CODE:
for fizzbuzz in range(50):
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
print("fizzbuzz")
continue
elif fizzbuzz % 3 == 0:
print("fizz")
continue
elif fizzbuzz % 5 == 0:
print("buzz")
continue
print(fizzbuzz)

5. Write a Python program to check the validity of


password input by users.
Validation :
• At least 1 letter between [a-z] and 1 letter between
[A-Z].
• At least 1 number between [0-9].
• At least 1 character from [$#@].
• Minimum length 6 characters.
• Maximum length 16 characters.

CODE:

import re

p= input("Input your password")

x = True

while x:

if (len(p)<6 or len(p)>12):

break

elif not re.search("[a-z]",p):

break

elif not re.search("[0-9]",p):

break
elif not re.search("[A-Z]",p):

break

elif not re.search("[$#@]",p):

break

elif re.search("\s",p):

break

else:

print("Valid Password")

x=False

break

if x:

print("Not a Valid Password")

6. Display Fibonacci series up to 10 terms


CODE:
# Program to display the Fibonacci sequence up to n-th
term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

7. Write a Python program that accepts a string and


calculate the number of digits and letters.
CODE:

s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)

8. Write a python program to get the following output

1-----99
2-----98
3-----97
..
..
..
98-----2
99-----1
CODE:

for x in range (1,100):

print(x,”———“,100-x);

9. Find the sum of the series 2 +22 + 222 + 2222 + .. n


terms
CODE:
Python3 code to find
# sum of series
# 2, 22, 222, ..
import math

# function which return


# the sum of series
def sumOfSeries( n ):
return 0.0246 * (math.pow(10, n) - 1 - (9 * n))

# driver code
n=3
print( sumOfSeries(n))

Programs on function

1] Write a computer program that, given the lengths of the two


sides of a right triangle adjacent to the right angle, computes the
length of the hypotenuse of the triangle.
CODE:
from math import sqrt
print("Input lengths of shorter triangle sides:")
a = float(input("a: "))
b = float(input("b: "))
c = sqrt(a**2 + b**2)
print("The length of the hypotenuse is:", c )

2] Write a guessing game program in which the computer


chooses at random an integer in the range 1….100. The user’s
goal is to guess the number in the least number of tries. For each
incorrect guess the user provides, the computer provides
feedback whether the user’s number is too high or too low.
CODE:

import random

num = random.randint(1, 100)

while True:

print('Guess a number between 1 and 100')

guess = input()

i = int(guess)

if i == num:

print('You won!!!')

break

elif i < num:

print('Try Higher')

elif i > num:

print('Try Lower')

#any recommendations for the game end

print('if you gussed less than 6 times you won')


3] Write a Python function that prints out the first n rows of
Pascal's triangle.

CODE:

def pascal_triangle(n):

trow = [1]

y = [0]

for x in range(max(n,0)):

print(trow)

trow=[l+r for l,r in zip(trow+y, y+trow)]

return n>=1

pascal_triangle(6)

4] Write a Python function to create and print a list where the


values are square of numbers between 1 and 30 (both included).

def printValues():

l = list()

for i in range(1,31):

l.append(i**2)

print(l)

printValues()

5]Write a Python program to detect the number of local variables


declared in a function.
def abc():

x=1

y=2

str1= "w3resource"

print("Python Exercises")

print(abc.__code__.co_nlocals)

6] Create a function showEmployee() in such a way that it should


accept employee name, and its salary and display both. If the
salary is missing in the function call assign default value 9000 to
salary.

def func(employee, salary=9000):

print('employee: ', employee )

print('Salary: ', salary)

func('Atharva', 30000)

func('Divya')

7] Python Program to Multiply Two Matrices by using function

CODE:

# take a 3x3 matrix

A = [[12, 7, 3],

[4, 5, 6],
[7, 8, 9]]

# take a 3x4 matrix

B = [[5, 8, 1, 2],

[6, 7, 3, 0],

[4, 5, 9, 1]]

result = [[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0]]

# iterating by row of A

for i in range(len(A)):

# iterating by column by B

for j in range(len(B[0])):

# iterating by rows of B

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]

for r in result:

print(r)

You might also like