A prime number in Python is any integer greater than 1 with no divisors other than 1 and itself. To check it, loop from 2 to int(n**0.5) + 1 and test n % i == 0. If no factor is found, the number is prime. Python handles this cleanly with a for loop, a while loop, or the math module.
- Prime check: loop from 2 to
int(n**0.5) + 1and testn % i == 0. - Fibonacci series: works with both a
forloop and awhileloop; output is identical. - Palindrome: compare a string or number against its reverse using slicing (
s == s[::-1]). - Pyramid pattern: nested loops print spaces and asterisks row by row.
- Stack: Python’s built-in
listacts as a stack using.append()and.pop().
Prime Number in Python: Two Working Versions
Every placement exam, college viva and entry-level interview in India asks candidates to write a prime checker. Exams like TCS NQT, Infosys InfyTQ, AMCAT and GATE CSE all test this pattern. It is one of the fastest ways to show you understand loops and conditionals together. According to a 2023 HackerRank Developer Skills Report, Python is the most-used language for coding assessments globally, so getting the prime number program in Python right matters from day one.
Version 1: Prime Number Program in Python Using a for Loop
This is the version most Indian university syllabi — including those of Anna University, Mumbai University and VTU — ask for. It checks divisibility up to the square root, which keeps it efficient even for large numbers. The square root limit works because if n has a factor larger than its square root, the corresponding paired factor must be smaller than the square root and would already have been found.
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
num = 29
if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Output: 29 is a prime number
Version 2: Check Prime Number in Python Using a while Loop
def is_prime_while(n):
if n <= 1:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
print(is_prime_while(37)) # True
print(is_prime_while(18)) # False
Output: True then False. Both versions produce the same result. The while loop gives you finer control over the counter, which is useful when you need to track the exact divisor that breaks primality.
Python Code for Fibonacci Series: for Loop and while Loop
The Fibonacci series is a sequence where each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13 and so on. It appears in algorithm courses, data structures modules and financial modelling. Stack Overflow’s 2023 Developer Survey found Python ranked first in “most-used language” for the fourth consecutive year, with Fibonacci being one of the top beginner search queries worldwide.
Fibonacci Series Using a for Loop
def fibonacci_for(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci_for(10)
Output: 0 1 1 2 3 5 8 13 21 34
Fibonacci Series Using a while Loop
def fibonacci_while(n):
a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1
fibonacci_while(10)
Output: 0 1 1 2 3 5 8 13 21 34
Both loops produce the same series. Use the for loop when you know the count in advance. Use the while loop when you want to keep going until a condition is met, such as printing Fibonacci numbers below a specific value.
| Approach | Loop Type | Best Used When | Time Complexity |
|---|---|---|---|
| Iterative Fibonacci | for loop | Fixed count of terms needed | O(n) |
| Iterative Fibonacci | while loop | Condition-based termination | O(n) |
| Recursive Fibonacci | Recursion | Clean code, small n only (n < 30) | O(2^n) |
| Memoised Fibonacci | functools.lru_cache | Large n, performance-critical | O(n) |
| Prime Check (sqrt method) | for or while loop | Single number primality check | O(sqrt n) |
If you are preparing for campus placements at IITs, NITs or tier-2 engineering colleges, understanding time complexity alongside the code is what separates candidates who clear the first round from those who do not. Mastering these patterns is one of the top skills every college student should build before graduation.
Palindrome Program in Python: Strings and Numbers
A palindrome reads the same forwards and backwards. “madam”, “racecar” and 121 are all palindromes. Python’s slicing makes the string check a one-liner, but knowing the while loop version for numbers is what interviewers in TCS, Wipro and Infosys hiring rounds actually want to see.
String Palindrome in Python
def is_palindrome_string(s):
s = s.lower().strip()
return s == s[::-1]
print(is_palindrome_string("Madam")) # True
print(is_palindrome_string("Python")) # False
Output: True then False. The .lower() call handles case sensitivity, which is a detail many beginners miss.
Palindrome Number in Python Using a while Loop
def is_palindrome_number(n):
original = n
reversed_num = 0
while n > 0:
digit = n % 10
reversed_num = reversed_num * 10 + digit
n //= 10
return original == reversed_num
print(is_palindrome_number(121)) # True
print(is_palindrome_number(123)) # False
Output: True then False. This logic reverses the integer digit by digit without converting it to a string, which is the approach most competitive programming problems and bank IT exam questions expect.
Palindrome Number in Python Using a for Loop
def is_palindrome_for(n):
s = str(n)
for i in range(len(s) // 2):
if s[i] != s[-(i + 1)]:
return False
return True
print(is_palindrome_for(1221)) # True
This compares characters from the outside in. It is marginally more readable for beginners and works equally well for palindrome strings in Python when you swap the integer for a string argument.
Pyramid Pattern and Stack in Python
Pyramid Pattern in Python
def pyramid(rows):
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
pyramid(5)
Output:
*
***
*****
*******
*********
Each row prints (rows - i) spaces followed by (2*i - 1) asterisks. Once you understand that formula, you can flip it, hollow it out, or replace asterisks with numbers in under a minute.
Stack Implementation in Python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return "Stack is empty"
def peek(self):
return self.items[-1] if self.items else "Stack is empty"
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
s = Stack()
s.push(10)
s.push(20)
s.push(30)
print(s.pop()) # 30
print(s.peek()) # 20
print(s.size()) # 2
Output: 30, 20, 2. Stacks are foundational for browser history, undo operations, expression evaluation and depth-first search. According to NASSCOM’s 2024 India Tech Talent Report (available at nasscom.in), data structures and algorithms rank among the top three skills Indian tech employers screen for in entry-level hiring.
If you want to turn these fundamentals into a job, check out what entry-level roles for fresh graduates actually look like in the current market. The best free online learning platforms for students in 2025 are a solid starting point before you invest in paid certification.
According to JetBrains’ State of Developer Ecosystem 2023 report — the most recent edition available at time of writing — 58% of Python developers use it primarily for data analysis and machine learning, while 84% started their Python journey with basic programs exactly like these. The foundation matters regardless of which specialisation you choose later.
Once you are comfortable with these patterns, the jump to object-oriented programming, APIs and frameworks like Django or Flask is much smaller than it looks. Our guide on choosing the right career path after graduation in 2026 breaks it down by role and salary band. You can also browse the best career options in 2026 for students and professionals to see where Python skills actually lead.
For those who want to build credentials that employers recognise, online courses aligned to high-salary jobs in 2025 are worth exploring early. 3.0 University’s certification courses cover Cybersecurity, Ethical Hacking, AI, Blockchain and Web3 with hands-on labs and mentorship.
Frequently Asked Questions
How do you check for a prime number in Python?
Loop from 2 to int(n**0.5) + 1 using a for or while loop. If n % i == 0 for any i in that range, the number is not prime. If the loop completes without finding a factor, the number is prime. Numbers less than or equal to 1 are never prime by definition.
How do you print a Fibonacci series in Python?
Start with a, b = 0, 1. In each iteration, print a, then update with a, b = b, a + b. A for loop works when you know the count of terms. A while loop works when you want to stop at a threshold value. Both produce identical output for the same input.
How do you check whether a string is a palindrome in Python?
The fastest way is s == s[::-1]. Always apply .lower().strip() first to handle case differences and whitespace. For a number, reverse it digit by digit using the modulus operator in a while loop and compare with the original. Both methods are expected in Indian university exams and placement rounds including TCS NQT and AMCAT.
How do you print a pyramid pattern in Python?
Use a for loop from 1 to rows + 1. Each row prints (rows - i) spaces followed by (2 * i - 1) asterisks. This formula produces a centred pyramid. You can modify it to print inverted pyramids, hollow pyramids or number patterns by changing what gets printed inside the inner loop.
How do you implement a stack in Python?
Use Python’s built-in list. Call .append(item) to push and .pop() to remove the top element. Wrap these in a class with peek(), is_empty() and size() methods for a clean, reusable structure. This covers stack implementation questions asked in GATE, AMCAT and most campus placement coding rounds.
These five programs — prime check, Fibonacci series, palindrome for strings and numbers, pyramid pattern and stack — cover roughly 60 to 70% of what Indian placement examiners test in the first coding round. Practice each version until you can write it from memory in under five minutes. Then move to variations: print all primes up to N, Fibonacci below a given value, or a hollow pyramid. That is where real fluency comes from.
Last updated: June 2025. Reviewed by the 3University editorial team.