Python Basic Programs: Practice with Example Codes
Eleven Python basics with working code: I/O handling, swap, factorial, Fibonacci, prime check, and string operations. Ideal for placement coding round practice.
Python basic programs are the entry point for every campus placement coding round: companies test I/O handling, loops, and string operations before moving to data structures.
Why placement coding rounds start with Python basics
TCS, Infosys, Wipro, and Cognizant all include a coding section in their campus hiring rounds. The questions in that section almost always start with basic I/O and control flow before escalating to arrays and linked lists. Students who hesitate on “swap two variables without a temporary variable” or “print the Fibonacci series up to n terms” lose time they need on the harder problems that follow.
Python is accepted on all major campus test platforms: AMCAT, CoCubes, and the company-specific portals used by the firms listed above. It runs on Python 3.x, which all placement platforms support. The programs below use only the standard library, so no third-party package installation is required.
One practical note: placement coding tests judge output exactly. If the expected output is Sum: 8.0 and you print Sum: 8, you may get zero credit. Pay attention to data types and formatting in every example here.
Input, output, and math: four programs that appear on every test
Hello World
Every language tutorial starts here. In Python, it is one line:
print("Hello, World!")
The print() function writes to the console. Placement tests rarely ask for Hello World directly, but knowing print() arguments well (separators, end characters, and string formatting) matters when you need to match exact output specifications.
Adding two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Sum:", num1 + num2)
input() always returns a string. float() converts it to a decimal number. Use int() when the problem guarantees whole-number input. The safe default is float() because it handles decimal inputs without raising an error.
Area of a circle
import math
radius = float(input("Enter radius: "))
area = math.pi * radius ** 2
print("Area:", round(area, 4))
The math module (Python 3 docs) provides math.pi as a high-precision constant. The ** operator handles exponentiation. round(area, 4) trims the output to 4 decimal places. Know this pattern: import math, access constants via math.constant_name, and use ** for powers.
Swap two variables
Python’s multiple assignment syntax handles the swap in one line:
a = 10
b = 20
a, b = b, a
print("a:", a, "b:", b)
The traditional three-step approach, required in languages without tuple unpacking:
temp = a
a = b
b = temp
Python’s tuple unpacking assigns both sides simultaneously before either variable changes. Placement tests ask for both versions; be ready to explain what each does in memory.
For a more complete treatment of these I/O patterns, see the Python Calculator Program.
Loops, conditions, and recursion
Factorial
The factorial of n is the product of every integer from 1 to n. Five factorial equals 1 × 2 × 3 × 4 × 5, which is 120.
Recursive approach:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # outputs 120
Iterative approach (no recursion depth risk):
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Placement tests sometimes ask which approach fails for large inputs. The recursive version hits Python’s default recursion depth limit. The iterative version does not.
Fibonacci series
n = int(input("How many terms? "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
A common placement variant: “Print Fibonacci terms until the value exceeds 1000.” Replace range(n) with a while a <= 1000: loop.
Prime number check
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(17)) # True
print(is_prime(18)) # False
Checking divisors only up to the square root of n cuts unnecessary iterations. For n = 100, that means checking 2 through 10 instead of 2 through 99. Same result, far fewer steps.
LCM and GCD
import math
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
gcd = math.gcd(num1, num2)
lcm = (num1 * num2) // gcd
print("GCD:", gcd)
print("LCM:", lcm)
math.gcd() is available in Python 3.5 and above. The LCM formula is (num1 * num2) // gcd. The // operator gives integer floor division, which is required here because LCM must be a whole number.
Armstrong Number Checker in Python uses the same loop-based digit-extraction logic and is worth practicing alongside the prime check.
Greatest of Three Numbers in Python covers conditional logic in a format that placement tests replicate closely.
String and list operations
Reverse a string
s = input("Enter a string: ")
print("Reversed:", s[::-1])
The slice s[::-1] reverses any Python sequence. Some placement tests ask you to reverse without slice notation. Use the reversed() built-in or write an explicit loop in that case.
Sort a string alphabetically
s = input("Enter a string: ")
print("Sorted:", "".join(sorted(s)))
sorted() returns a list of characters in ascending ASCII order. "".join() stitches them back into a string. Pass reverse=True to sorted() for descending order. See Sort a String in Python for the full breakdown including case-insensitive sorting.
Sum of list elements
numbers = [10, 20, 30, 40, 50]
total = sum(numbers)
print("Sum:", total)
Python’s built-in sum() handles this in one call. If the problem asks for the running total printed at each step, use a loop and accumulate into a variable.
How to practice these before a placement test
Reading code and running code produce different results in timed tests. The students who clear placement coding rounds consistently are the ones who type each program from scratch at least twice, then test it with edge cases: zero input to the factorial function, a negative number in the prime checker, an empty string in the string reverser. That edge-case mindset is what separates a passing score from a strong one.
Once each program runs correctly with normal input, practice combining patterns. A calculator that handles division by zero, a Fibonacci generator that stops when a user types a sentinel value, or a string sorter that also counts vowel frequency. That layering of I/O, loops, and string handling is what builds real Python fluency.
If you want to take these Python basics further and build something that actually calls an AI model, TinkerLLM is the starting point at ₹299: the same I/O and loop patterns from this article applied to language model API calls instead of console output.
Primary sources
Frequently asked questions
How do I run a Python program on my laptop?
Install Python 3.x from python.org, save your code as a .py file, and run it from the terminal or Command Prompt using: python filename.py
Which Python programs are asked in TCS NQT?
TCS NQT tests basic I/O, control flow (loops and conditions), string handling, and simple algorithms. These are the same categories this guide covers.
What is the difference between / and // in Python?
The / operator returns a float (5/2 returns 2.5), while // is integer floor division (5//2 returns 2). Placement tests frequently check this distinction.
How do I write factorial in Python without recursion?
Use a loop: start with result = 1, then multiply by each integer from 1 to n using range(1, n+1). This avoids recursion depth issues for large inputs.
Is Python accepted in campus placement coding rounds?
Yes. TCS, Infosys, Wipro, and Cognizant all accept Python in their online test platforms alongside C, C++, and Java.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)