📘 50 Basic Python Problems (Conditionals & Loops Only)

Click the eye button 👁 to reveal solutions — each shows Brute Force and an Optimized variant.

Prime Pattern String List

1. Print the first 10 natural numbers

Loops
Brute Force
for i in range(1, 11):
    print(i)
Optimized
print(*range(1, 11))

2. Sum of first N natural numbers

Loops, Arithmetic
Brute Force
n = int(input())
s = 0
for i in range(1, n+1):
    s += i
print(s)
Optimized
n = int(input())
print(n*(n+1)//2)

3. Factorial of a number

Loops
Brute Force
n = int(input())
f = 1
for i in range(1, n+1):
    f *= i
print(f)
Optimized
import math
n = int(input())
print(math.factorial(n))

4. Multiplication table of N (1..10)

Loops
Brute Force
n = int(input())
for i in range(1, 11):
    print(n, 'x', i, '=', n*i)
Optimized
n = int(input())
print('\n'.join(f"{n} x {i} = {n*i}" for i in range(1, 11)))

5. Reverse an integer

Loops, Arithmetic
Brute Force
n = int(input())
rev = 0
while n > 0:
    rev = rev*10 + n%10
    n //= 10
print(rev)
Optimized
print(input()[::-1])

6. Check if a number is prime

Conditionals, Loops
Brute Force
n = int(input())
if n < 2:
    print('Not Prime')
else:
    ok = True
    for i in range(2, n):
        if n % i == 0:
            ok = False; break
    print('Prime' if ok else 'Not Prime')
Optimized
import math
n = int(input())
if n < 2:
    print('Not Prime')
else:
    ok = True
    for i in range(2, int(math.isqrt(n))+1):
        if n % i == 0:
            ok = False; break
    print('Prime' if ok else 'Not Prime')

7. GCD of two numbers

Loops
Brute Force
a,b = map(int, input().split())
ans = 1
for i in range(1, min(a,b)+1):
    if a%i==0 and b%i==0:
        ans = i
print(ans)
Optimized
import math
a,b = map(int, input().split())
print(math.gcd(a,b))

8. Check palindrome string

Strings, Conditionals
Brute Force
s = input().strip()
rev = ''
for ch in s:
    rev = ch + rev
print('Palindrome' if s == rev else 'Not Palindrome')
Optimized
s = input().strip()
print('Palindrome' if s == s[::-1] else 'Not Palindrome')

9. Fibonacci series up to N terms

Loops
Brute Force
n = int(input())
a,b = 0,1
for _ in range(n):
    print(a, end=' ')
    a,b = b,a+b
Optimized
def fib(n):
    a,b = 0,1
    for _ in range(n):
        yield a
        a,b = b,a+b
print(*fib(int(input())))

10. Largest of three numbers

Conditionals
Brute Force
a,b,c = map(int, input().split())
if a>=b and a>=c: print(a)
elif b>=a and b>=c: print(b)
else: print(c)
Optimized
a,b,c = map(int, input().split())
print(max(a,b,c))

11. Count digits of an integer

Loops
Brute Force
n = int(input())
if n == 0:
    print(1)
else:
    c = 0
    while n:
        c += 1
        n //= 10
    print(c)
Optimized
s = input().strip()
print(len(s.lstrip('-')))

12. Sum of digits of an integer

Loops
Brute Force
n = int(input())
s = 0
n = abs(n)
while n:
    s += n%10
    n //= 10
print(s)
Optimized
print(sum(int(ch) for ch in input().strip() if ch.isdigit()))

13. Check Armstrong number (n-digit)

Loops, Conditionals
Brute Force
x = input().strip()
n = int(x)
p = len(x)
s = 0
t = n
while t:
    d = t%10
    # power via loop
    powv = 1
    for _ in range(p):
        powv *= d
    s += powv
    t //= 10
print('Armstrong' if s==n else 'Not Armstrong')
Optimized
x = input().strip()
n = int(x)
p = len(x)
print('Armstrong' if sum(int(c)**p for c in x)==n else 'Not Armstrong')

14. Check leap year

Conditionals
Brute Force
y = int(input())
if (y%400==0) or (y%4==0 and y%100!=0):
    print('Leap')
else:
    print('Not Leap')
Optimized
y = int(input())
print('Leap' if (y%400==0) or (y%4==0 and y%100!=0) else 'Not Leap')

15. Print even numbers up to N

Loops
Brute Force
n = int(input())
for i in range(1, n+1):
    if i%2==0:
        print(i, end=' ')
Optimized
n = int(input())
print(*range(2, n+1, 2))

16. Print odd numbers up to N

Loops
Brute Force
n = int(input())
for i in range(1, n+1):
    if i%2==1:
        print(i, end=' ')
Optimized
n = int(input())
print(*range(1, n+1, 2))

17. Sum of even numbers up to N

Loops, Arithmetic
Brute Force
n = int(input())
s = 0
for i in range(2, n+1, 2):
    s += i
print(s)
Optimized
n = int(input())
k = n//2
print(k*(k+1))  # sum of first k evens = k(k+1)

18. Sum of odd numbers up to N

Loops, Arithmetic
Brute Force
n = int(input())
s = 0
for i in range(1, n+1, 2):
    s += i
print(s)
Optimized
n = int(input())
k = (n+1)//2
print(k*k)  # sum of first k odds = k^2

19. Count vowels in a string

Strings, Loops
Brute Force
s = input().lower()
v = 0
for ch in s:
    if ch in 'aeiou':
        v += 1
print(v)
Optimized
s = input().lower()
print(sum(ch in 'aeiou' for ch in s))

20. Print all factors of N

Loops
Brute Force
n = int(input())
for i in range(1, n+1):
    if n % i == 0:
        print(i, end=' ')
Optimized
import math
n = int(input())
res = []
for i in range(1, int(math.isqrt(n))+1):
    if n % i == 0:
        res.append(i)
        if i*i != n:
            res.append(n//i)
print(*sorted(res))

21. Check perfect number

Loops, Conditionals
Brute Force
n = int(input())
s = 0
for i in range(1, n):
    if n % i == 0:
        s += i
print('Perfect' if s==n else 'Not Perfect')
Optimized
import math
n = int(input())
s = 1 if n>1 else 0
for i in range(2, int(math.isqrt(n))+1):
    if n % i == 0:
        s += i
        if i*i != n:
            s += n//i
print('Perfect' if s==n else 'Not Perfect')

22. Prime numbers in a range [L, R]

Loops
Brute Force
L, R = map(int, input().split())
for n in range(L, R+1):
    if n < 2: continue
    ok = True
    for i in range(2, n):
      if n % i == 0:
        ok = False; break
    if ok: print(n, end=' ')
Optimized
import math
L, R = map(int, input().split())
for n in range(L, R+1):
    if n < 2: continue
    ok = True
    for i in range(2, int(math.isqrt(n))+1):
        if n % i == 0:
            ok = False; break
    if ok: print(n, end=' ')

23. LCM of two numbers

Loops/Math
Brute Force
a,b = map(int, input().split())
m = max(a,b)
while True:
    if m%a==0 and m%b==0:
        print(m); break
    m += 1
Optimized
import math
a,b = map(int, input().split())
print(a*b // math.gcd(a,b))

24. Strong number check (sum of factorial of digits)

Loops
Brute Force
n = int(input())
orig = n
s = 0
while n:
    d = n%10
    f = 1
    for i in range(1, d+1):
        f *= i
    s += f
    n //= 10
print('Strong' if s==orig else 'Not Strong')
Optimized
import math
n = input().strip()
print('Strong' if sum(math.factorial(int(c)) for c in n)==int(n) else 'Not Strong')

25. Count words in a sentence

Strings
Brute Force
s = input().strip()
count, inword = 0, False
for ch in s + ' ':
    if ch.isspace():
        if inword: count += 1
        inword = False
    else:
        inword = True
print(count)
Optimized
print(len(input().split()))

26. Remove spaces from a string

Strings
Brute Force
s = input()
res = ''
for ch in s:
    if ch != ' ':
        res += ch
print(res)
Optimized
print(input().replace(' ', ''))

27. Character frequency dictionary

Strings, Loops
Brute Force
s = input().strip()
f = {}
for ch in s:
    if ch in f: f[ch] += 1
    else: f[ch] = 1
print(f)
Optimized
from collections import Counter
print(dict(Counter(input().strip())))

28. Maximum of a list

Lists, Loops
Brute Force
arr = list(map(int, input().split()))
mx = arr[0]
for x in arr:
    if x > mx:
        mx = x
print(mx)
Optimized
print(max(map(int, input().split())))

29. Second largest in a list

Lists, Loops
Brute Force
arr = list(map(int, input().split()))
first = second = -10**18
for x in arr:
    if x > first:
        second, first = first, x
    elif first > x > second:
        second = x
print(second)
Optimized
arr = sorted(set(map(int, input().split())))
print(arr[-2] if len(arr) > 1 else arr[0])

30. Bubble sort (ascending)

Lists, Loops
Brute Force
a = list(map(int, input().split()))
for i in range(len(a)):
    for j in range(0, len(a)-i-1):
        if a[j] > a[j+1]:
            a[j], a[j+1] = a[j+1], a[j]
print(*a)
Optimized
print(*sorted(map(int, input().split())))

31. Merge two lists and remove duplicates

Lists
Brute Force
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = []
for x in a + b:
    if x not in res:
        res.append(x)
print(*res)
Optimized
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(*sorted(set(a+b)))

32. Check if substring exists

Strings
Brute Force
s = input().strip()
sub = input().strip()
found = False
for i in range(len(s)-len(sub)+1):
    ok = True
    for j in range(len(sub)):
        if s[i+j] != sub[j]:
            ok = False; break
    if ok: found = True; break
print('Yes' if found else 'No')
Optimized
s = input().strip(); sub = input().strip()
print('Yes' if sub in s else 'No')

33. Count vowels & consonants

Strings
Brute Force
s = input().lower()
v=c=0
for ch in s:
    if ch.isalpha():
        if ch in 'aeiou': v+=1
        else: c+=1
print(v, c)
Optimized
s = input().lower()
V = set('aeiou')
letters = [ch for ch in s if ch.isalpha()]
print(sum(ch in V for ch in letters), sum(ch not in V for ch in letters))

34. Decimal to binary

Loops
Brute Force
n = int(input())
if n == 0: print(0)
else:
    bits = ''
    while n:
        bits = str(n%2) + bits
        n //= 2
    print(bits)
Optimized
print(bin(int(input()))[2:])

35. Binary to decimal

Loops
Brute Force
s = input().strip()
val = 0
for ch in s:
    val = val*2 + (ch=='1')
print(val)
Optimized
print(int(input().strip(), 2))

36. Power a^b

Loops
Brute Force
a,b = map(int, input().split())
res = 1
for _ in range(b):
    res *= a
print(res)
Optimized
a,b = map(int, input().split())
print(pow(a,b))

37. Sum of squares 1^2 + 2^2 + ... + n^2

Loops, Arithmetic
Brute Force
n = int(input())
s = 0
for i in range(1, n+1):
    s += i*i
print(s)
Optimized
n = int(input())
print(n*(n+1)*(2*n+1)//6)

38. Sum of cubes 1^3 + 2^3 + ... + n^3

Loops, Arithmetic
Brute Force
n = int(input())
s = 0
for i in range(1, n+1):
    s += i**3
print(s)
Optimized
n = int(input())
print((n*(n+1)//2)**2)

39. Print a grid: tables 1..10 (10x10)

Nested Loops
Brute Force
for i in range(1, 11):
    for j in range(1, 11):
        print(i*j, end='\t')
    print()
Optimized
print('\n'.join('\t'.join(str(i*j) for j in range(1,11)) for i in range(1,11)))

40. Reverse a string

Strings
Brute Force
s = input().strip()
rev = ''
for ch in s:
    rev = ch + rev
print(rev)
Optimized
print(input().strip()[::-1])

41. Check anagram (two strings)

Strings
Brute Force
a = input().replace(' ', '').lower()
b = input().replace(' ', '').lower()
if len(a)!=len(b):
    print('No')
else:
    da, db = {}, {}
    for ch in a:
        da[ch] = da.get(ch,0)+1
    for ch in b:
        db[ch] = db.get(ch,0)+1
    print('Yes' if da==db else 'No')
Optimized
a = sorted(input().replace(' ', '').lower())
b = sorted(input().replace(' ', '').lower())
print('Yes' if a==b else 'No')

42. Check palindrome number

Loops/Strings
Brute Force
n = int(input())
orign = n
rev = 0
while n:
    rev = rev*10 + n%10
    n //= 10
print('Yes' if rev==orign else 'No')
Optimized
s = input().strip()
print('Yes' if s==s[::-1] else 'No')

43. Count occurrences of an element in a list

Lists
Brute Force
arr = list(map(int, input().split()))
x = int(input())
c = 0
for v in arr:
    if v == x:
        c += 1
print(c)
Optimized
arr = list(map(int, input().split()))
x = int(input())
print(arr.count(x))

44. Index of first occurrence

Lists
Brute Force
a = input().split()
x = input().strip()
idx = -1
for i,v in enumerate(a):
    if v == x:
        idx = i; break
print(idx)
Optimized
a = input().split(); x = input().strip()
try:
    print(a.index(x))
except ValueError:
    print(-1)

45. Rotate list by k positions (right)

Lists
Brute Force
a = input().split(); k = int(input())
k %= len(a)
for _ in range(k):
    x = a.pop()
    a.insert(0, x)
print(*a)
Optimized
a = input().split(); k = int(input())
k %= len(a)
print(*(a[-k:]+a[:-k] if k else a))

46. Remove duplicates (preserve order)

Lists
Brute Force
a = input().split()
res = []
for x in a:
    if x not in res:
        res.append(x)
print(*res)
Optimized
a = input().split()
print(*dict.fromkeys(a))

47. Print n terms of AP (a, d)

Loops
Brute Force
a, d, n = map(int, input().split())
cur = a
for _ in range(n):
    print(cur, end=' ')
    cur += d
Optimized
a, d, n = map(int, input().split())
print(*[a + i*d for i in range(n)])

48. Compute nCr

Loops/Math
Brute Force
n, r = map(int, input().split())
# compute factorial via loop
f = [1]*(n+1)
for i in range(2, n+1):
    f[i] = f[i-1]*i
print(f[n]//(f[r]*f[n-r]))
Optimized
import math
n, r = map(int, input().split())
print(math.comb(n, r))

49. Number triangle pattern

Patterns, Nested Loops
Brute Force
n = int(input())
for i in range(1, n+1):
    for j in range(1, i+1):
        print(j, end=' ')
    print()
Optimized
n = int(input())
print('\n'.join(' '.join(str(j) for j in range(1, i+1)) for i in range(1, n+1)))

50. FizzBuzz (1..N)

Conditionals, Loops
Brute Force
n = int(input())
for i in range(1, n+1):
    if i%15==0: print('FizzBuzz')
    elif i%3==0: print('Fizz')
    elif i%5==0: print('Buzz')
    else: print(i)
Optimized
n = int(input())
print('\n'.join('FizzBuzz' if i%15==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else str(i)
                for i in range(1, n+1)))