Practical Python Lessons Beginner
Practical Python Lessons Beginner
Code:
print('Hello, Python World!')
Task: Ask the user for their name and age, then print a greeting.
Code:
name = input('What is your name? ')
age = input('How old are you? ')
print('Hello', name, '! You are', age, 'years old.')
Task: Create a simple calculator that adds, subtracts, multiplies, and divides two numbers.
Code:
a = float(input('Enter first number: '))
b = float(input('Enter second number: '))
print('Sum:', a + b)
print('Difference:', a - b)
print('Product:', a * b)
print('Quotient:', a / b)
Code:
num = int(input('Enter a number: '))
if num % 2 == 0:
print('Even')
else:
print('Odd')
Task: User has to guess a number between 1 and 10. Give feedback.
Code:
import random
guess = 0
number = random.randint(1, 10)
while guess != number:
guess = int(input('Guess the number (1-10): '))
if guess < number:
print('Too low!')
elif guess > number:
print('Too high!')
else:
print('Correct!')
Code:
students = ['Alice', 'Bob', 'Cathy', 'David', 'Eve']
for student in students:
print('Student:', student)
Task: Ask the user for a message, save it, then read it back.
Code:
msg = input('Write a message to save: ')
with open('message.txt', 'w') as file:
file.write(msg)
Code:
# Add tasks
tasks = []
while True:
task = input('Enter a task (or type done): ')
if task.lower() == 'done':
break
tasks.append(task)
# Save tasks
with open('todo.txt', 'w') as file:
for task in tasks:
file.write(task + '\n')
# Read tasks
print('Your To-Do List:')
with open('todo.txt', 'r') as file:
for line in file:
print('-', line.strip())