Python – CRT Crash Sheet
Shortened Textbook Edition
Introduction
This Python CRT Crash Sheet is a comprehensive study guide designed for Campus Recruitment Training (CRT) examination preparation. Python
has become one of the most sought-after languages in technical interviews due to its simplicity, readability, and powerful features. This guide
covers essential Python concepts from basic syntax to advanced programming techniques, along with 25 most commonly asked interview
problems. Each program is presented with clear logic explanation, complete working code, and sample input/output. Additionally, pattern
programs strengthen logical thinking and problem-solving skills. This document serves as a quick reference during exam preparation and coding
interviews.
Core Syntax Overview
Variables and Data Types:
int, float, str, bool, list, tuple, dict, set
Dynamic typing: Python automatically determines type
Assignment: var_name = value
Input/Output:
input() – Read string from user
print() – Display output
Formatted strings: f"text {var}"
input() always returns string, use int(), float() to convert
Operators:
Arithmetic: +, -, *, /, //, %, **
Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Assignment: =, +=, -=, *=, /=
Control Statements:
if, elif, else – Decision making
Ternary: value1 if condition else value2
pass – Do nothing placeholder
Loops:
for – Iterate over sequence
while – Condition-based loop
range() – Generate sequence of numbers
break, continue – Loop control
Functions:
Define: def function_name(parameters):
Return: return value
Default parameters: def func(x, y=5):
Calling: function_name(arguments)
Lists:
Create: list = [1, 2, 3]
Access: list[index]
Methods: append(), extend(), pop(), remove(), sort(), reverse()
Slicing: list[start:end:step]
Tuples:
Immutable list: tuple = (1, 2, 3)
Single element: tuple = (1,) (comma required)
Unpacking: a, b, c = (1, 2, 3)
Dictionaries:
Create: dict = {"key": value, "name": "John"}
Access: dict["key"]
Methods: keys(), values(), items(), get(), pop()
Strings:
Create: str = "Hello"
Methods: len(), upper(), lower(), replace(), split(), join(), find(), strip()
Indexing and slicing work like lists
File Handling:
Open: file = open("filename", "mode")
Modes: "r" read, "w" write, "a" append
Read: [Link](), [Link](), [Link]()
Write: [Link]()
Close: [Link]() or use with statement
Top 25 Most Important Python Programs
1. Even or Odd
Logic: Check if number is divisible by 2 using modulo operator.
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")
Sample Input/Output:
Enter a number: 7
7 is Odd
Enter a number: 10
10 is Even
2. Factorial
Logic: Multiply all numbers from 1 to n.
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial of negative number is undefined")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
Sample Input/Output:
Enter a number: 5
Factorial of 5 is 120
Enter a number: 0
Factorial of 0 is 1
3. Fibonacci Series
Logic: Each number is sum of previous two numbers.
n = int(input("Enter number of terms: "))
a, b = 0, 1
series = []
for i in range(n):
[Link](a)
a, b = b, a + b
print("Fibonacci Series:", series)
Sample Input/Output:
Enter number of terms: 7
Fibonacci Series: [0, 1, 1, 2, 3, 5, 8]
4. Prime Check
Logic: Check if number has no divisors except 1 and itself.
num = int(input("Enter a number: "))
if num < 2:
print(f"{num} is not Prime")
else:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is Prime")
else:
print(f"{num} is not Prime")
Sample Input/Output:
Enter a number: 13
13 is Prime
Enter a number: 20
20 is not Prime
5. Palindrome Number
Logic: Reverse the number and compare with original.
num = int(input("Enter a number: "))
original = num
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
if original == reversed_num:
print(f"{original} is Palindrome")
else:
print(f"{original} is not Palindrome")
Sample Input/Output:
Enter a number: 121
121 is Palindrome
Enter a number: 123
123 is not Palindrome
6. Armstrong Number
Logic: Sum of digits each raised to power of digit count equals original number.
num = int(input("Enter a number: "))
original = num
digits = len(str(num))
sum_powers = 0
while num > 0:
digit = num % 10
sum_powers += digit ** digits
num //= 10
if original == sum_powers:
print(f"{original} is Armstrong Number")
else:
print(f"{original} is not Armstrong Number")
Sample Input/Output:
Enter a number: 153
153 is Armstrong Number
Enter a number: 154
154 is not Armstrong Number
7. Reverse Number
Logic: Extract digits and build reversed number.
num = int(input("Enter a number: "))
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
print(f"Reversed Number: {reversed_num}")
Sample Input/Output:
Enter a number: 12345
Reversed Number: 54321
8. Sum of Digits
Logic: Extract each digit and add to sum.
num = int(input("Enter a number: "))
sum_digits = 0
while num > 0:
sum_digits += num % 10
num //= 10
print(f"Sum of digits: {sum_digits}")
Sample Input/Output:
Enter a number: 12345
Sum of digits: 15
9. GCD (Greatest Common Divisor)
Logic: Use Euclidean algorithm.
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"GCD of {num1} and {num2} is {gcd(num1, num2)}")
Sample Input/Output:
Enter first number: 48
Enter second number: 18
GCD of 48 and 18 is 6
10. LCM (Least Common Multiple)
Logic: LCM = (a × b) / GCD(a, b).
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
lcm = (num1 * num2) // gcd(num1, num2)
print(f"LCM of {num1} and {num2} is {lcm}")
Sample Input/Output:
Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is 36
11. Leap Year
Logic: Divisible by 4, not by 100 unless by 400.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a Leap Year")
else:
print(f"{year} is not a Leap Year")
Sample Input/Output:
Enter a year: 2020
2020 is a Leap Year
Enter a year: 1900
1900 is not a Leap Year
12. Swap Two Numbers
Logic: Use simultaneous assignment or temporary variable.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Before Swap: a = {a}, b = {b}")
# Method 1: Using simultaneous assignment (Python way)
a, b = b, a
print(f"After Swap: a = {a}, b = {b}")
Sample Input/Output:
Enter first number: 5
Enter second number: 10
Before Swap: a = 5, b = 10
After Swap: a = 10, b = 5
13. String Length
Logic: Use len() function to get string length.
string = input("Enter a string: ")
length = len(string)
print(f"Length of string: {length}")
Sample Input/Output:
Enter a string: Hello
Length of string: 5
14. Reverse String
Logic: Use slicing with negative step.
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"Reversed String: {reversed_string}")
Sample Input/Output:
Enter a string: Hello
Reversed String: olleH
15. String Palindrome
Logic: Compare string with its reverse.
string = input("Enter a string: ")
reversed_string = string[::-1]
if string == reversed_string:
print(f"{string} is a Palindrome String")
else:
print(f"{string} is not a Palindrome String")
Sample Input/Output:
Enter a string: racecar
racecar is a Palindrome String
Enter a string: hello
hello is not a Palindrome String
16. Count Vowels
Logic: Iterate through string and count vowels.
string = input("Enter a string: ").lower()
vowels = "aeiou"
count = 0
for char in string:
if char in vowels:
count += 1
print(f"Number of vowels: {count}")
Sample Input/Output:
Enter a string: Hello World
Number of vowels: 3
17. Largest Element in List
Logic: Use max() function or iterate through list.
n = int(input("Enter list size: "))
list_elements = []
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
list_elements.append(num)
largest = max(list_elements)
print(f"Largest element: {largest}")
Sample Input/Output:
Enter list size: 5
Enter element 1: 10
Enter element 2: 25
Enter element 3: 15
Enter element 4: 30
Enter element 5: 20
Largest element: 30
18. Sum of List Elements
Logic: Use sum() function or iterate.
n = int(input("Enter list size: "))
list_elements = []
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
list_elements.append(num)
total = sum(list_elements)
print(f"Sum of list elements: {total}")
Sample Input/Output:
Enter list size: 5
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Sum of list elements: 150
19. Bubble Sort
Logic: Compare adjacent elements and swap.
n = int(input("Enter list size: "))
list_elements = []
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
list_elements.append(num)
# Bubble sort
for i in range(n):
for j in range(n - i - 1):
if list_elements[j] > list_elements[j + 1]:
list_elements[j], list_elements[j + 1] = list_elements[j + 1], list_elements[j]
print(f"Sorted list: {list_elements}")
Sample Input/Output:
Enter list size: 5
Enter element 1: 64
Enter element 2: 34
Enter element 3: 25
Enter element 4: 12
Enter element 5: 22
Sorted list: [12, 22, 25, 34, 64]
20. Linear Search
Logic: Search by comparing each element.
n = int(input("Enter list size: "))
list_elements = []
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
list_elements.append(num)
search = int(input("Enter element to search: "))
found = -1
for i in range(n):
if list_elements[i] == search:
found = i
break
if found != -1:
print(f"Element found at index {found}")
else:
print("Element not found")
Sample Input/Output:
Enter list size: 5
Enter element 1: 10
Enter element 2: 25
Enter element 3: 15
Enter element 4: 30
Enter element 5: 20
Enter element to search: 15
Element found at index 2
21. Binary Search
Logic: Divide and search in sorted array.
n = int(input("Enter list size: "))
list_elements = []
print("Enter sorted array elements:")
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
list_elements.append(num)
search = int(input("Enter element to search: "))
low, high = 0, n - 1
found = -1
while low <= high:
mid = (low + high) // 2
if list_elements[mid] == search:
found = mid
break
elif list_elements[mid] < search:
low = mid + 1
else:
high = mid - 1
if found != -1:
print(f"Element found at index {found}")
else:
print("Element not found")
Sample Input/Output:
Enter list size: 5
Enter sorted array elements:
Enter element 1: 10
Enter element 2: 15
Enter element 3: 20
Enter element 4: 25
Enter element 5: 30
Enter element to search: 20
Element found at index 2
22. Matrix Addition
Logic: Add corresponding elements of two matrices.
m, n = map(int, input("Enter dimensions (rows columns): ").split())
matrix_a = []
print("Enter Matrix A elements:")
for i in range(m):
row = list(map(int, input(f"Row {i+1}: ").split()))
matrix_a.append(row)
matrix_b = []
print("Enter Matrix B elements:")
for i in range(m):
row = list(map(int, input(f"Row {i+1}: ").split()))
matrix_b.append(row)
matrix_c = [[matrix_a[i][j] + matrix_b[i][j] for j in range(n)] for i in range(m)]
print("Resulting Matrix:")
for row in matrix_c:
print(row)
Sample Input/Output:
Enter dimensions (rows columns): 2 2
Enter Matrix A elements:
Row 1: 1 2
Row 2: 3 4
Enter Matrix B elements:
Row 1: 5 6
Row 2: 7 8
Resulting Matrix:
[6, 8]
[10, 12]
23. Transpose of Matrix
Logic: Swap rows and columns.
m, n = map(int, input("Enter dimensions (rows columns): ").split())
matrix = []
print("Enter matrix elements:")
for i in range(m):
row = list(map(int, input(f"Row {i+1}: ").split()))
[Link](row)
transpose = [[matrix[i][j] for i in range(m)] for j in range(n)]
print("Transposed Matrix:")
for row in transpose:
print(row)
Sample Input/Output:
Enter dimensions (rows columns): 2 3
Enter matrix elements:
Row 1: 1 2 3
Row 2: 4 5 6
Transposed Matrix:
[1, 4]
[2, 5]
[3, 6]
24. File Read/Write
Logic: Write to file, then read from it.
# Writing to file
with open("[Link]", "w") as file:
data = input("Enter text to write: ")
[Link](data)
# Reading from file
print("\nContent of file:")
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Sample Input/Output:
Enter text to write: Hello World
Content of file:
Hello World
25. Recursive Factorial
Logic: Function calls itself with n-1 until base case.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
num = int(input("Enter a number: "))
if num < 0:
print("Factorial of negative number is undefined")
else:
result = factorial(num)
print(f"Factorial of {num} is {result}")
Sample Input/Output:
Enter a number: 5
Factorial of 5 is 120
Pattern Programs
Pattern 1: Right-Angled Triangle
Logic: Print i asterisks in each row.
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
print("* " * i)
Sample Output (n=5):
*
* *
* * *
* * * *
* * * * *
Pattern 2: Inverted Triangle
Logic: Print (n-i+1) asterisks in each row.
n = int(input("Enter number of rows: "))
for i in range(n, 0, -1):
print("* " * i)
Sample Output (n=5):
* * * * *
* * * *
* * *
* *
*
Pattern 3: Pyramid
Logic: Print spaces followed by asterisks.
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
spaces = " " * (n - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)
Sample Output (n=5):
*
***
*****
*******
*********
Last-Minute Summary
Quick Syntax Patterns:
1. Input/Output:
input() returns string
Convert: int(), float(), str()
Print: print(value) or f-string f"text {var}"
2. Data Structures:
List: [1, 2, 3] – mutable, ordered
Tuple: (1, 2, 3) – immutable
Dict: {"key": value} – key-value pairs
Set: {1, 2, 3} – unique values
3. Loops:
for i in range(n): – iterate n times
for item in list: – iterate through list
while condition: – condition-based loop
4. Functions:
def func_name(params): – define
return value – return result
Lambda: lambda x: x**2 – anonymous function
5. List Operations:
Append: [Link](item)
Slicing: list[start:end:step]
Comprehension: [x*2 for x in list]
6. String Operations:
Reverse: string[::-1]
Split: [Link](delimiter)
Join: [Link](list)
Case: upper(), lower()
7. File Handling:
with open("[Link]", "r") as file:
content = [Link]()
Exam Tips:
Always initialize variables before use
Use meaningful variable names
Test with edge cases
Add comments explaining logic
Use in operator for membership checks
Use range() for loops efficiently
Apply list comprehensions for concise code
Remember tuple immutability
Use if __name__ == "__main__": for script execution
Use try-except for error handling
Common Mistakes to Avoid:
Off-by-one errors in loops
Forgetting colon after function/loop definitions
Using = instead of == in comparisons
Mutable default arguments in functions
Modifying list while iterating
Forgetting to close files
Confusing append() and extend()
Revision Checklist:
✓ Variables and data types
✓ Input/output operations
✓ Conditional statements
✓ Loops (for, while, break, continue)
✓ Lists and list operations
✓ Tuples and dictionaries
✓ Strings and string methods
✓ Functions and recursion
✓ File handling
✓ Sorting and searching algorithms
✓ Pattern programs
✓ Error handling
End of Document