I need to write a python code for the following problem:
-Write functions to ask the user for a positive integer n and and integer x and display the sum of the series:
1+𝑥1⁄1!+𝑥2⁄2!+𝑥3⁄3!+⋯+𝑥𝑛⁄𝑛!
Requirement:
so basically, it needs to ask the user for positive int (n) and positive int (x) to solve 1+𝑥1⁄1!+𝑥2⁄2!+𝑥3⁄3!+⋯+𝑥𝑛⁄𝑛! and then display the sum. it should be two equations I think and no math libraries.
This is the code I have so far:
n = int(input('Enter a positive integer: '))
x = int(input('Enter another positive integer: '))
# n >= 0
fact(x)
I am stuck on how to continue past the user input, should i use a for loop or?
n = int(input('Enter a positive integer: '))
# x = int(input('Enter another positive integer: '))
answer = 1
for i in range (n,0,-1):
result = answer*i
print(n, answer)
so, i figured out how to do just the factorial, but now how do i the rest of the equation?
Write functions to ask the user for a positive integer n and and integer x and ...
What you need is a function, so, for the first step, I strongly encourage you to avoid using the print
function. It seems, in addition to the problem you mentioned, there are some logical errors too. Since the problem has required you to write functions, I intended to solve it using these functions as much as possible. What I have come up with is what follows:
# 4. No importing was intended
# 2. Write a function to calculate factorials for a number.
def fact(n):
mult = 1
for i in range(1, n+1):
mult *= i
return mult
# 3. Write a function to calculate factorials for a number.
def sum_series(s):
temp = 0
for value in s:
temp += value
return temp
def main():
n = input('Enter a positive integer: ')
x = input('Enter another positive integer: ')
# 1. Input validation
if not n.isnumeric():
return False
if not x.isnumeric():
return False
n = int(n)
x = int(x)
tempSeries = [1]
for i in range (1,n+1):
tempSeries.append((x**i)/fact(i))
return sum_series(tempSeries)
So, if we gave 2 as n and 3 as x we would have something like:
1 + (3^1)/1 + (3^2)/2 = 8.5
Let's check the function:
main()
Enter a positive integer: 2
Enter another positive integer: 3
8.5