Code is a set of instructions that tell a computer what to do. It's like a recipe for a computer to follow. Just as you follow steps to bake a cake, a computer follows code to perform tasks.
In Python, we write code using simple, English-like commands that the computer can understand and execute.
In Python, we use the print() function to display text or values on the screen. It's often the first thing beginners learn because it's simple and helps you see the results of your code.
1print("Hello, World!")
pyThis will display "Hello, World!" when you run the code.
You can print multiple items by separating them with commas:
1print("Hello,", "World!")
pyNow, let's practice using print statements to display some personal information.
Exercise: Create a new Python file and use print statements to display the following information about yourself:
Here's an example of how your code might look:
1print("My name is Alice")
2print("I am 25 years old")
3print("My favorite color is blue")
4print("My hobby is playing guitar")
pyTry running this code and then modify it with your own information!
Remember, coding is about experimenting and learning. Don't be afraid to try different things and see what happens!
Variables are containers for storing data values. In Python, you can think of variables as labeled boxes that hold information.
1age = 25
2name = "Alice"
3print(age) # Output: 25
4print(name) # Output: Alice
py1integer_num = 42
2float_num = 3.14
3text = "Python is fun"
4is_true = True
py1# Good variable names
2user_age = 30
3first_name = "John"
4
5# Avoid these
61st_place = "Gold" # Invalid: starts with a number
7for = "Loop" # Invalid: 'for' is a Python keyword
pyYou can combine strings and variables using the + operator or f-strings (formatted string literals).
1name = "Alice"
2age = 25
3
4# Using + operator
5print("My name is " + name + " and I am " + str(age) + " years old.")
6
7# Using f-string (recommended)
8print(f"My name is {name} and I am {age} years old.")
pyPractice creating variables of different types and printing them:
1# Create variables of different types
2my_name = "Your Name"
3my_age = 20
4my_height = 1.75
5is_student = True
6
7# Print the variables
8print(f"Name: {my_name}")
9print(f"Age: {my_age}")
10print(f"Height: {my_height} meters")
11print(f"Is a student: {is_student}")
12
13# Create a sentence using the variables
14print(f"{my_name} is {my_age} years old, {my_height} meters tall, and it's {is_student} that they are a student.")
pyTry running this code and then modify it with your own information!
Python supports basic arithmetic operations using the following symbols:
1a = 10
2b = 3
3print(f"Addition: {a + b}") # Output: 13
4print(f"Subtraction: {a - b}") # Output: 7
5print(f"Multiplication: {a * b}") # Output: 30
6print(f"Division: {a / b}") # Output: 3.3333...
py1a = 10
2b = 3
3print(f"Modulus: {a % b}") # Output: 1
4print(f"Exponentiation: {a ** b}") # Output: 1000
5print(f"Floor division: {a // b}") # Output: 3
pyPython follows the PEMDAS rule for the order of operations:
1result = 5 + 3 * 2 ** 2 - (6 + 2) / 2
2print(f"Result: {result}") # Output: 15.0
pyThe input() function allows you to get user input from the console.
1name = input("Enter your name: ")
2print(f"Hello, {name}!")
pyThe input() function always returns a string. To use it as a number, you need to convert it:
1age_str = input("Enter your age: ")
2age = int(age_str)
3print(f"Next year, you will be {age + 1} years old.")
4
5height_str = input("Enter your height in meters: ")
6height = float(height_str)
7print(f"Your height in centimeters is {height * 100} cm.")
pyLet's create a simple calculator that can perform basic arithmetic operations:
1# Simple calculator
2num1 = float(input("Enter the first number: "))
3num2 = float(input("Enter the second number: "))
4operation = input("Enter the operation (+, -, *, /): ")
5
6if operation == "+":
7 result = num1 + num2
8elif operation == "-":
9 result = num1 - num2
10elif operation == "*":
11 result = num1 * num2
12elif operation == "/":
13if num2 != 0:
14 result = num1 / num2
15else:
16 result = "Error: Division by zero"
17else:
18 result = "Error: Invalid operation"
19
20print(f"Result: {result}")
pyTry running this code and test it with different numbers and operations!
If statements allow you to execute code based on certain conditions. The basic syntax is:
1if condition:
2 # code to execute if condition is True
pyExample:
1age = 18
2if age >= 18:
3 print("You are an adult.")
py'else' provides an alternative when the 'if' condition is False. 'elif' (else if) allows you to check multiple conditions.
1age = 15
2if age >= 18:
3 print("You are an adult.")
4elif age >= 13:
5 print("You are a teenager.")
6else:
7 print("You are a child.")
pyPython uses these comparison operators:
1x = 5
2y = 10
3print(x > y) # False
4print(x < y) # True
5print(x == y) # False
6print(x != y) # True
7print(x >= 5) # True
8print(y <= 7) # False
pyYou can combine conditions using 'and', 'or', and 'not':
1age = 25
2has_license = True
3
4if age >= 18 and has_license:
5 print("You can drive.")
6
7temperature = 28
8if temperature > 30 or temperature < 0:
9 print("Extreme weather!")
10
11is_raining = False
12if not is_raining:
13 print("It's a sunny day!")
pyLet's create a simple program that determines a person's life stage and activities based on their age:
1# Life stage and activity determiner
2
3age = int(input("Enter your age: "))
4
5if age < 0:
6 print("Invalid age entered.")
7elif age < 5:
8 print("You're a baby. Time for a nap!")
9elif age < 13:
10 print("You're a child. Let's play some games!")
11elif age < 20:
12 print("You're a teenager. How about learning a new skill?")
13elif age < 65:
14 print("You're an adult. Time to work or pursue your passions!")
15else:
16 print("You're a senior. Enjoy your retirement!")
17
18# Additional conditions
19if age >= 18:
20 print("You can vote in elections.")
21if age >= 21:
22 print("You can also run for political office.")
23
24if age < 16:
25 print("You can't drive yet.")
26elif 16 <= age < 18:
27 print("You can drive with restrictions.")
28else:
29 print("You can drive without restrictions.")
pyTry running this code with different ages and see how the output changes!
Lists are ordered collections of items in Python. They can contain elements of different types.
1# Creating a list
2fruits = ["apple", "banana", "cherry"]
3print(fruits)
4
5# Lists can contain different types
6mixed_list = [1, "hello", 3.14, True]
7print(mixed_list)
pyPython provides various operations to work with lists:
1fruits = ["apple", "banana", "cherry", "date"]
2
3# Indexing (accessing elements)
4print(fruits[0]) # First element
5print(fruits[-1]) # Last element
6
7# Slicing
8print(fruits[1:3]) # Elements from index 1 to 2
9
10# Appending (adding to the end)
11fruits.append("elderberry")
12print(fruits)
13
14# Removing
15fruits.remove("banana")
16print(fruits)
17
18# Length of a list
19print(len(fruits))
pyFor loops allow you to iterate over sequences like lists.
1fruits = ["apple", "banana", "cherry"]
2
3# Looping through a list
4for fruit in fruits:
5 print(f"I like {fruit}")
6
7# Using range() function
8for i in range(5):
9 print(i)
10
11# Looping with index
12for index, fruit in enumerate(fruits):
13 print(f"Index {index}: {fruit}")
pyWhile loops repeat as long as a condition is true.
1# Counting up
2count = 0
3while count < 5:
4 print(count)
5 count += 1
6
7# User input loop
8while True:
9 answer = input("Do you want to continue? (yes/no): ")
10 if answer.lower() != 'yes':
11 break
12print("Loop ended")
pyLet's create a simple task management program using lists and loops:
1# Task Management Program
2
3tasks = []
4
5while True:
6print("\n--- Task Manager ---")
7print("1. Add task")
8print("2. View tasks")
9print("3. Mark task as done")
10print("4. Exit")
11
12choice = input("Enter your choice (1-4): ")
13
14if choice == '1':
15 task = input("Enter a new task: ")
16 tasks.append(task)
17 print("Task added successfully!")
18
19elif choice == '2':
20 if tasks:
21 print("\nYour tasks:")
22 for index, task in enumerate(tasks, start=1):
23 print(f"{index}. {task}")
24 else:
25 print("No tasks yet!")
26
27elif choice == '3':
28 if tasks:
29 print("\nYour tasks:")
30 for index, task in enumerate(tasks, start=1):
31 print(f"{index}. {task}")
32 task_num = int(input("Enter the number of the completed task: "))
33 if 1 <= task_num <= len(tasks):
34 done_task = tasks.pop(task_num - 1)
35 print(f"Task '{done_task}' marked as done!")
36 else:
37 print("Invalid task number!")
38 else:
39 print("No tasks to mark as done!")
40
41elif choice == '4':
42 print("Thank you for using Task Manager. Goodbye!")
43 break
44
45else:
46 print("Invalid choice. Please try again.")
pyThis program demonstrates the use of lists and loops to create a simple task management system. It allows users to add tasks, view tasks, mark tasks as done, and exit the program.
1# Functions are reusable blocks of code
2# They help organize and simplify your program
3
4def say_hello():
5 print("Hello!")
6
7# Using the function
8say_hello()
py1# Parameters: inputs to a function
2# Return values: output from a function
3
4def add(a, b):
5 return a + b
6
7result = add(3, 4)
8print(result) # Prints: 7
py1# Modules are pre-written code you can use
2# We'll use 'random' for generating random numbers
3
4import random
5
6# Generate a random number between 1 and 10
7number = random.randint(1, 10)
8print(number)
py1# An if inside another if
2
3age = 16
4if age >= 13:
5 print("You're a teenager")
6 if age >= 18:
7 print("You're also an adult")
py1# A loop inside another loop
2
3for i in range(3):
4 for j in range(2):
5 print(f"{i}-{j}")
py1# Exits a loop early
2
3for i in range(5):
4 if i == 3:
5 break
6 print(i)
7# Prints: 0, 1, 2
py1# Skips to the next loop iteration
2
3for i in range(5):
4 if i == 2:
5 continue
6 print(i)
7# Prints: 0, 1, 3, 4
py1secret = 5
2guess = int(input("Guess a number (1-10): "))
3
4if guess == secret:
5 print("You got it!")
6else:
7 if guess < secret:
8 print("Too low")
9 else:
10 print("Too high")
11
12 guess = int(input("Try again: "))
13 if guess == secret:
14 print("You got it on the second try!")
15 else:
16 print(f"Sorry, it was {secret}")
py1# A class is like a blueprint for creating objects
2# An object is an instance of a class
3
4class Dog:
5 pass
6
7my_dog = Dog() # Creating an object
py1# Attributes are variables that belong to a class
2# Methods are functions that belong to a class
3
4class Dog:
5 # Attribute
6 breed = "Labrador"
7
8 # Method
9 def bark(self):
10 print("Woof!")
11
12my_dog = Dog()
13print(my_dog.breed) # Prints: Labrador
14my_dog.bark() # Prints: Woof!
py1# The __init__ method is called when creating a new object
2# It's used to set up initial values for the object
3
4class Dog:
5 def __init__(self, name, age):
6 self.name = name
7 self.age = age
8
9my_dog = Dog("Buddy", 3)
10print(my_dog.name) # Prints: Buddy
11print(my_dog.age) # Prints: 3
py