Alternating series
Class 11 Computer Science · Iterative Statements: Series · Complete the program · 4 marks
- Read the question and the sample tests.
- Write your Python program in the editor.
- Run Code to check it on the sample tests (no marks).
- Submit Answer for evaluation: hidden tests award the marks. Nothing is saved here.
Question
Complete the program below. It reads integers x and n and prints the sum of the alternating series 1 − x + x² − x³ + x⁴ − ... ± xⁿ (the terms with an odd power of x are subtracted). Replace each blank ____ with the correct code. Input: two lines, x and n (n is 0 or more). Output: exactly one line in the form Sum = S
Sample tests
Use these examples to check your program. Your output must match the Expected Output exactly.
2 3
Sum = -5
3 2
Sum = 7
Evaluation: when you submit, your program is also checked against 4 hidden tests that you cannot see. Marks come from the hidden tests only. Each test you pass earns its marks, so a partly correct program gets part marks. Prompt text passed to input() is not counted as output.
Your program
Write the whole program, including any import lines it needs. The editor starts empty; Reset Code clears it. Submit your answer before leaving the page.
Approach (open it after you have tried)
The sign depends on the power: even powers (i % 2 == 0) are added and odd powers are subtracted with s = s - x ** i. For x = 2 and n = 3 the terms are 1 - 2 + 4 - 8 = -5.
Practise all 65 Class 11 programs
This page has 10 programs. The complete Class 11 Python Lab has 65, and keeps your best score and chapter progress.
Other Class 11 programs: Simple interest · Grade from marks · Prime or composite · Right triangle of stars · Palindrome string · Linear search in a list · Search in a tuple · Character frequency with a dictionary · Circle with the math module