Python is a versatile and beginner-friendly language! Here are some simple code examples covering fundamental concepts.
1. Hello, World! (Basic Output)
The classic first program.
# This is a comment. Comments are ignored by the Python interpreter.
print("Hello, World!")
print("Python is fun!")
Explanation:
print()is a built-in function that displays output to the console.- Text inside double quotes (
"") is called a string.
2. Variables and Data Types
Variables are used to store data. Python automatically determines the data type.
# Integers (whole numbers)
age = 30
score = 150
# Floating-point numbers (numbers with decimal points)
price = 19.99
pi = 3.14159
# Strings (sequences of characters)
name = "Alice"
city = 'New York' # Single quotes also work for strings
# Booleans (True or False values)
is_student = True
has_license = False
# Printing variables
print("Name:", name)
print("Age:", age)
print("Price:", price)
print("Is student:", is_student)
# You can also change a variable's value
age = 31
print("New Age:", age)
Explanation:
- You assign a value to a variable using the
=operator. - Python supports different data types like
int,float,str, andbool. - You can print multiple items by separating them with commas in the
print()function.
3. User Input
Get information directly from the user.
# Get a string input
user_name = input("Enter your name: ")
print("Hello,", user_name + "!")
# Get a number input (input() always returns a string, so convert it)
fav_number_str = input("What's your favorite number? ")
fav_number = int(fav_number_str) # Convert the string to an integer
print("Your favorite number is:", fav_number)
print("Your favorite number doubled is:", fav_number * 2)
Explanation:
input()displays a prompt to the user and waits for them to type something and press Enter. It always returns the input as a string.int()is used to convert a string to an integer. You can also usefloat()for decimal numbers.
4. Conditional Statements (if, elif, else)
Execute different code blocks based on conditions.
age = 17
if age >= 18:
print("You are an adult.")
print("You can vote.")
elif age >= 13: # This condition is checked if the first 'if' is False
print("You are a teenager.")
else: # This block runs if all previous conditions are False
print("You are a child.")
# Another example
temperature = 25
if temperature > 30:
print("It's hot outside!")
elif temperature < 10:
print("It's cold outside!")
else:
print("The weather is moderate.")
Explanation:
if,elif(else if), andelsedefine blocks of code.- Indentation is crucial in Python! Code blocks are defined by indentation (typically 4 spaces).
- Conditions use comparison operators:
>(greater than),<(less than),>=(greater than or equal to),<=(less than or equal to),==(equal to),!=(not equal to).
5. Loops (for loop and while loop)
Repeat a block of code multiple times.
a) For Loop (Iterating over a sequence)
# Iterate over a list of items
fruits = ["apple", "banana", "cherry"]
print("My favorite fruits:")
for fruit in fruits:
print(fruit)
# Iterate a specific number of times using range()
print("\nCounting from 0 to 4:")
for i in range(5): # range(5) generates numbers 0, 1, 2, 3, 4
print(i)
print("\nCounting from 1 to 5:")
for i in range(1, 6): # range(start, end+1)
print(i)
Explanation:
- The
forloop is excellent for iterating over collections (like lists) or a sequence of numbers generated byrange().
b) While Loop (Repeating as long as a condition is true)
count = 0
print("Counting up to 3:")
while count < 3:
print(count)
count = count + 1 # Increment the count, otherwise it's an infinite loop!
print("Loop finished.")
# A simple guessing game
secret_number = 7
guess = 0
while guess != secret_number:
guess_str = input("Guess the secret number (1-10): ")
guess = int(guess_str)
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
print("Congratulations! You guessed it:", secret_number)
Explanation:
- The
whileloop continues to execute its block of code as long as its condition remainsTrue. - It's important to ensure that the condition eventually becomes
Falseto avoid an infinite loop.
6. Functions
Group related code into reusable blocks.
# Define a simple function with no parameters
def say_hello():
print("Hello there!")
print("Welcome to Python functions.")
# Call the function
say_hello()
say_hello() # You can call it multiple times
# Define a function with parameters
def greet(name):
print(f"Hi, {name}!") # f-string for easy string formatting
# Call the function with an argument
greet("Alice")
greet("Bob")
# Define a function that returns a value
def add_numbers(a, b):
sum_result = a + b
return sum_result # The function sends back this value
# Use the returned value
result = add_numbers(5, 3)
print("The sum is:", result)
another_sum = add_numbers(10, 20)
print("Another sum is:", another_sum)
Explanation:
defis used to define a function.- Parameters are variables listed inside the parentheses in the function definition (e.g.,
name,a,b). - Arguments are the actual values passed to the function when it's called.
returnsends a value back from the function. If a function doesn't have areturnstatement, it implicitly returnsNone.
7. Lists (Ordered, Changeable Collections)
Store multiple items in a single variable.
# Creating a list
my_list = [1, 2, 3, "apple", True]
print("My list:", my_list)
# Accessing elements by index (lists are 0-indexed)
print("First element:", my_list[0]) # Output: 1
print("Fourth element:", my_list[3]) # Output: apple
# Changing an element
my_list[1] = "banana"
print("List after change:", my_list)
# Adding elements
my_list.append("orange") # Adds to the end
print("List after append:", my_list)
# Length of the list
print("Length of list:", len(my_list))
# Slicing a list (getting a sub-list)
print("Slice from index 1 to 3 (exclusive):", my_list[1:4])
Explanation:
- Lists are defined using square brackets
[]. - Elements are ordered, meaning they have an index (position).
- Lists are "mutable," meaning you can change, add, or remove elements after creation.
8. Dictionaries (Key-Value Pairs)
Store data in key-value pairs, like a real-world dictionary.
# Creating a dictionary
person = {
"name": "Charlie",
"age": 28,
"city": "London",
"is_student": False
}
print("Person dictionary:", person)
# Accessing values by key
print("Name:", person["name"])
print("Age:", person["age"])
# Adding a new key-value pair
person["occupation"] = "Engineer"
print("After adding occupation:", person)
# Modifying a value
person["age"] = 29
print("After changing age:", person)
# Getting all keys or values
print("All keys:", person.keys())
print("All values:", person.values())
# Iterating through a dictionary
print("\nPerson details:")
for key, value in person.items():
print(f"{key}: {value}")
Explanation:
- Dictionaries are defined using curly braces
{}with key-value pairs separated by colons. - Keys must be unique and immutable (like strings, numbers, tuples). Values can be anything.
- Access values using
dictionary_name[key].
How to Run This Code
- Save: Copy and paste the code into a text editor (like Notepad, VS Code, Sublime Text, Atom) and save it with a
.pyextension (e.g.,my_examples.py). - Open Terminal/Command Prompt: Navigate to the directory where you saved the file.
- Run: Type
python my_examples.pyand press Enter.
These examples should give you a solid foundation for understanding basic Python programming!