Answer:
1)
h = 19 # h is already assigned a positive integer value 19
i = 1 # used to calculate perfect square
q = 0 # stores the sum of the perfect squares
while q < h:
# this loop executes until value of number of perfect squares is less than h
q = q + (i*i) # to calculate the sum of perfect squares
i = i + 1 # increments i by 1 at every iteration
print(q) # displays the sum of perfect squares
Output:
30
Step-by-step explanation:
Here we see that the sum of the perfect square is printed in the output i.e. 30. If we want to assign value 4 to q then we should alter the code as following:
h = 19
i = 1
sum_of_ps = 0
q=0
while sum_of_ps < h:
sum_of_ps = sum_of_ps + (i*i)
q = q + 1
i = i + 1
print(q)
If you want to take input from the user and also display the perfect squares in output you can use the following code:
h = int(input('Enter the value of h: ')) #takes value of h from user
i = 1
sum_of_ps = 0
q=0
while sum_of_ps < h:
sum_of_ps = sum_of_ps + (i*i)
print(i*i) #displays the perfect squares of h
q = q + 1
i = i + 1
print(sum_of_ps) #displays sum of perfect squares
print(q) #displays number of perfect squares whose value is less than h
Output:
1
4
9
16
30
4
2)
# k and m are already assigned positive integers 10 and 40
k = 10
m = 40
i = 1 # i is initialized to 1
q = 0 # q stores the number of perfect squares between k and m
while i*i < m: # loop computes perfect square of numbers between k and m
if i*i > k:
q = q + 1 # counts the number of perfect squares
i = i + 1 #increments the value of i at each iteration
print (q) # prints the no of perfect squares between k and m
If you want to display the perfect squares too use , add print(i*i) statement after if statement if i*i > k:
Output:
3
3)
def Fibonacci(n): # method Fibonacci which has an integer parameter n
if n <= 1: # if the value of n is less than or equals to 1
result = n # stores the value of n into result
elif n > 1: # else if the value of n is greater than 1
result = Fibonacci(n-1) + Fibonacci(n-2)
# calls Fibonacci method recursively to associate nth value of Fibonacci #sequence with variable result
return result #returns the final value stored in result variable
print(Fibonacci(8))
#calls Fibonacci function and passes value 8 to it
Output:
21