Python Programming: Examples and Tips for INFO2000 Midterm
General Python Tips:
- Loops: Use
for i in range(start, stop, step):
for iteration. - Lists:
my_list = [1, 2, 3]
, access elements withmy_list[index]
. - Dictionaries:
my_dict = {'key': 'value'}
, access withmy_dict['key']
. - Functions: Use
def function_name(parameters): return value
to define. - Importing Libraries: Use
import random
,import math
. - Printing Debugging Info: Use
print(variable)
. - String Manipulation:
.upper()
,.lower()
,.strip()
,.split()
,.join()
. - File Handling:
open('filename.txt', 'r')
to read,open('filename.txt', 'w')
to write.
1. Sum of Even Numbers (56 to 102)
print(sum(range(56, 103, 2)))
range(56, 103, 2)
generates even numbers.sum()
computes the total.
2. List of Prime Numbers (100 to 200)
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
primes = [n for n in range(100, 201) if is_prime(n)]
print(primes)
- Efficiency Tip: Checking up to
sqrt(n)
reduces iterations.
3. Rabbit & Turtle Race Simulation
import random
def race():
rabbit, turtle = 0, 0
while rabbit < 50 and turtle < 50:
rabbit += random.randint(1, 10)
turtle += random.randint(1, 3)
print(f"Rabbit: {rabbit}, Turtle: {turtle}")
print("Winner:", "Rabbit" if rabbit > turtle else "Turtle")
race()
4. Number Guessing Game
import random
number = random.randint(1, 99)
low, high = 1, 99
while True:
guess = int(input(f"Guess a number between {low} and {high}: "))
if guess == number:
print("Correct!")
break
elif guess < number:
low = guess + 1
else:
high = guess - 1
5. Rock-Paper-Scissors Game
import random
choices = ["rock", "paper", "scissors"]
player = input("Choose rock, paper, or scissors: ").lower()
computer = random.choice(choices)
print(f"Computer chose {computer}")
if player == computer:
print("It's a tie!")
elif (player == "rock" and computer == "scissors") or \
(player == "scissors" and computer == "paper") or \
(player == "paper" and computer == "rock"):
print("You win!")
else:
print("You lose!")
6. Pascal’s Triangle
def pascal(n):
triangle = [[1]]
for i in range(1, n):
row = [1] + [triangle[i-1][j] + triangle[i-1][j+1] for j in range(len(triangle[i-1])-1)] + [1]
triangle.append(row)
for row in triangle:
print(row)
pascal(5)
7. Magic Square (n x n)
def magic_square(n):
magic = [[0] * n for _ in range(n)]
i, j = 0, n // 2
for num in range(1, n * n + 1):
magic[i][j] = num
i -= 1
j += 1
if num % n == 0:
i += 2
j -= 1
elif i < 0:
i = n - 1
elif j == n:
j = 0
for row in magic:
print(row)
magic_square(3)
8. DNA Nucleotide Frequency
def count_nucleotides(file):
with open(file, 'r') as f:
dna = f.read().strip()
counts = {nucleotide: dna.count(nucleotide) for nucleotide in "ACGT"}
print(counts)
count_nucleotides("dna.txt")
9. List of Names (First Letter & Length)
names = ["Alice", "Bob", "Charlie", "David", "Eve"]
info = [(name[0], len(name)) for name in names]
print(info)
10. Lottery Ball Selection (1-49)
import random
lottery = random.sample(range(1, 50), 6)
print(sorted(lottery))
Useful Libraries & Functions
random.randint(a, b)
: Random integer betweena
andb
.math.sqrt(x)
: Square root.len(list)
: Get list length.list.append(x)
: Addx
to a list.string.lower()
,string.upper()
: Convert case.sorted(list)
: Sort elements.input(prompt)
: Get user input.open(file, mode)
: File handling ('r'
for read,'w'
for write).
Extra Notes:
try-except
for Error Handling:
try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
while
vs.for
loops:while condition:
runs indefinitely until condition is false.for item in iterable:
iterates over an object.
This should cover everything you need for the mid-term! Good luck!