Write a program that asks for the user's name and prints a greeting.
name = input('Enter your name: ')
print('Hello,', name)
Write a program that checks if a number is positive.
num = int(input('Enter a number: '))
if num > 0:
print('Positive')
Write a program that prints numbers 1 to 10 using a loop.
for i in range(1, 11):
print(i)
Write a function that returns the square of a number.
def square(n):
return n * n
print(square(4))
Write a program that writes a message to a file.
with open('output.txt', 'w') as f:
f.write('Hello, file!')
Write a program that stores and prints a list of fruits.
fruits = ['apple', 'banana', 'cherry']
print(fruits)
Write a program that counts vowels in a string.
s = input('Enter a string: ')
vowels = 'aeiouAEIOU'
count = sum(1 for c in s if c in vowels)
print('Vowels:', count)
Write a program that stores and retrieves a phone book using a dictionary.
phonebook = {'Alice': '123', 'Bob': '456'}
print(phonebook['Alice'])
Write a program that reads a file, counts word frequencies, and stores them in a dictionary.
filename = input('Enter file: ')
with open(filename) as f:
text = f.read()
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)
Write a program that asks for two numbers and displays their sum.
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('Sum:', num1 + num2)
Write a program that asks for a password and validates it.
password = input('Enter password: ')
if password == 'secret':
print('Access granted')
Write a program that calculates the sum of all numbers from 1 to 100.
total = 0
for i in range(1, 101):
total += i
print('Sum:', total)
Write a program that uses a function to convert inches to centimeters.
def inches_to_cm(inches):
return inches * 2.54
print(inches_to_cm(10))
Write a program that reads and prints contents of a file.
with open('output.txt', 'r') as f:
print(f.read())
Write a program that finds the largest number in a list.
nums = [3, 8, 2, 5]
print('Largest:', max(nums))
Write a program that checks if a string is a palindrome.
s = input('Enter a string: ')
print('Palindrome' if s == s[::-1] else 'Not palindrome')
Write a program that counts word frequencies in a string using a dictionary.
text = 'hello world hello'
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)
Write a program that prompts for numbers until 'done', saves them in a list, and calculates stats.
nums = []
while True:
entry = input('Enter number or done: ')
if entry == 'done': break
nums.append(float(entry))
print(min(nums), max(nums), sum(nums)/len(nums))
Write a program that converts Fahrenheit to Celsius.
fahrenheit = float(input('Enter temperature in Fahrenheit: '))
celsius = (fahrenheit - 32) * 5/9
print('Celsius:', celsius)
Write a program that determines if a number is even or odd.
num = int(input('Enter a number: '))
if num % 2 == 0:
print('Even')
else:
print('Odd')
Write a program that asks the user for input until they type 'exit'.
while True:
text = input('Enter something: ')
if text == 'exit':
break
Write a program with a function that checks if a number is prime.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(7))
Write a program that counts the number of lines in a file.
with open('output.txt') as f:
lines = f.readlines()
print('Line count:', len(lines))
Write a program that removes all negative numbers from a list.
nums = [1, -2, 3, -4, 5]
positive = [n for n in nums if n >= 0]
print(positive)
Write a program that replaces all spaces in a string with underscores.
s = input('Enter a string: ')
print(s.replace(' ', '_'))
Write a program that removes duplicates from a list using a set.
nums = [1, 2, 2, 3]
unique = set(nums)
print(unique)
Write a program that asks for name/score pairs, stores in dict, and prints the top 3 scorers.
def get_score(item):
return item[1]
scores = {}
while True:
name = input('Enter name: ')
if name == 'done': break
score = int(input('Enter score: '))
scores[name] = score
sorted_scores = sorted(scores.items(), key=get_score, reverse=True)
print(sorted_scores[:3])
Write a program that asks for the user's age and calculates birth year.
age = int(input('Enter your age: '))
import datetime
year = datetime.datetime.now().year - age
print('You were born in', year)
Write a program that checks if a year is a leap year.
year = int(input('Enter a year: '))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print('Leap Year')
else:
print('Not Leap Year')
Write a program that prints a multiplication table.
num = int(input('Enter a number: '))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Write a function that returns the largest of three numbers.
def largest(a, b, c):
return max(a, b, c)
print(largest(3, 7, 5))
Write a program that reads numbers from a file and calculates their total.
with open('numbers.txt') as f:
total = sum(int(line) for line in f)
print('Total:', total)
Write a program that reverses a list.
nums = [1, 2, 3, 4]
nums.reverse()
print(nums)
Write a program that capitalizes the first letter of each word.
s = input('Enter a string: ')
print(' '.join(word.capitalize() for word in s.split()))
Write a program that finds common elements between two sets.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 & set2)
Write a program that reads names from a file, removes duplicates, sorts them, and writes to a new file.
with open('names.txt') as f:
names = sorted(set(f.read().splitlines()))
with open('unique_sorted.txt', 'w') as f:
f.write('\n'.join(names))
Write a program that takes three numbers and displays their average.
a = float(input('Enter first number: '))
b = float(input('Enter second number: '))
c = float(input('Enter third number: '))
print('Average:', (a + b + c)/3)
Write a program that asks for a score and prints the grade (A-F).
score = int(input('Enter score: '))
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('F')
Write a program that finds the factorial of a number.
num = int(input('Enter a number: '))
fact = 1
for i in range(1, num+1):
fact *= i
print('Factorial:', fact)
Write a program with functions to calculate the area of a circle, square, and triangle.
import math
def area_circle(r): return math.pi * r**2
def area_square(s): return s**2
def area_triangle(b, h): return 0.5 * b * h
print(area_circle(3), area_square(4), area_triangle(3, 6))
Write a program that writes user input to a file until 'stop' is typed.
with open('output.txt', 'w') as f:
while True:
text = input('Enter text: ')
if text == 'stop':
break
f.write(text + '\n')
Write a program that reads numbers into a list and displays mean, median, and mode.
import statistics
nums = [1, 2, 2, 3, 4]
print(statistics.mean(nums), statistics.median(nums), statistics.mode(nums))
Write a program that encrypts a string using Caesar cipher.
s = input('Enter text: ')
shift = 3
encrypted = ''.join(chr((ord(c) - 97 + shift) % 26 + 97) if c.islower() else c for c in s)
print(encrypted)
Write a program that merges two dictionaries and sums values of common keys.
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {k: d1.get(k, 0) + d2.get(k, 0) for k in set(d1) | set(d2)}
print(merged)
Create a mini-address book program that allows user to add, search, and delete entries using dicts and files.
def menu():
print('1. Add\n2. Search\n3. Delete\n4. Quit')
book = {}
while True:
menu()
choice = input('> ')
if choice == '1':
name = input('Name: ')
number = input('Number: ')
book[name] = number
elif choice == '2':
name = input('Name: ')
print(book.get(name, 'Not found'))
elif choice == '3':
name = input('Name: ')
book.pop(name, None)
elif choice == '4':
break