USING THE PYTHON LANGUAGE 1. a) Exercise 1 In mathematics, the factorial of a no
ID: 3585569 • Letter: U
Question
USING THE PYTHON LANGUAGE
1. a)
Exercise 1 In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1. For this exercise, create a function called factorial that takes a single integer parameter n and returns n!. Write this function using a while loop. Have your program prompt the user for an integer, call your function and then print the result to the terminal.
b)
Modify the function you wrote in the previous exercise to accomplish the same goal using a for loop.
c)
Write a function that will cycle through a string and count the number of vowels contained in the string (feel free to reuse or modify any code you may have laying around to accomplish this task). Finish this exercise by prompting the user for a string, call your function passing the input string and reporting the number of vowels to the user.
d)
write a program that will continually ask the user to enter integers until they enter one that is divisible by 1, 2, 3, 4 and 5
Explanation / Answer
def factorial_1(n):#factorial using iterative while loop
fact =1
while(n>0):#calculating factorial
fact = fact*n
n=n-1
return(fact)
def factorial_2(n):#factorial using iterative for loop
fact =1
for i in range (n):#calculating factorial
fact = fact*(i+1)
return(fact)
def num_vowels(s):
l = ['a','e','i','o','u','A','E','I','O','U']
n = len(s)
c=0 #to store the count of vowels in s
for i in range(n):
if s[i] in l:
c=c+1
return(c) #returning the count
def divisible():#divisible by 1,2,3,4,5
l = [1,2,3,4,5]
while(True):
n = int(input("Enter a number :"))
for i in range(len(l)):
if(n%l[i]!=0):#if not divisible by any number then breaking
break
if (i==len(l)-1):#divisible by all 1,2,3,4,5
return
n = int(input("Enter a number of find factorial:"))
print("Factorial of ",n,"is",factorial_1(n))
print("Factorial of ",n,"is",factorial_2(n))
s = input("Enter a string :")
print("The number of vowels in ",s," :",num_vowels(s))
divisible()
output:
>>>
Enter a number of find factorial:5
Factorial of 5 is 120
Factorial of 5 is 120
Enter a string :hello
The number of vowels in hello : 2
Enter a number :5
Enter a number :10
Enter a number :20
Enter a number :24
Enter a number :120
>>>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.