Learn › Class 11 › Computer Science / Informatics Practices › Python programming fundamentals
Python fundamentals
Example 1: Sum of the first n natural numbers
Open one step at a time. Try the next step yourself first.
- Step 1. n = int(input('Enter n: '))
Show step 2
total = 0
Show step 3
for i in range(1, n + 1): total = total + i
Show step 4
print(total). For n = 5 it prints 15.
Example 2: Even or odd with a function
Open one step at a time. Try the next step yourself first.
- Step 1. def parity(x): return 'even' if x % 2 == 0 else 'odd'
Show step 2
parity(14) returns 'even' because 14 % 2 is 0.
Show step 3
parity(9) returns 'odd' because 9 % 2 is 1.