DEV Community

tamilvanan
tamilvanan

Posted on

Learn Python 003

Note: I’m not an expert. I’m writing this blog just to document my learning journey. πŸš€


1. πŸ” Functions with Parameters and Return Values

So far, you’ve seen this:

def greet(name):
    print("Hello,", name)
Enter fullscreen mode Exit fullscreen mode

But functions can also return values:

def square(x):
    return x * x

result = square(5)
print(result)  # 25
Enter fullscreen mode Exit fullscreen mode

βœ… What's new here:

  • return sends a result back from the function.
  • Now you can use the result later in your code.

🧠 Why it matters:

Functions become tools.
Instead of just doing something, they calculate and give back answers.


2. πŸ“š Lists β€” Storing Many Items Together

A list is a sequence of items.

fruits = ["apple", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

You can:

print(fruits[0])         # "apple"
print(len(fruits))       # 3
fruits.append("orange")  # Add new item
Enter fullscreen mode Exit fullscreen mode

You can loop over lists:

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

🧠 Why it matters:

Lists let you work with collections β€” shopping carts, scores, to-do items.


3. πŸ” Useful List Tricks

numbers = [10, 20, 30, 40]

print(sum(numbers))         # 100
print(max(numbers))         # 40
print(min(numbers))         # 10
numbers.sort()              # sort in place
Enter fullscreen mode Exit fullscreen mode

🧠 These built-in tools save time and reduce errors.


4. πŸ—‚οΈ Dictionaries β€” Store Things by Name

A dictionary stores values using keys (names) instead of positions.

person = {
    "name": "Alice",
    "age": 30,
    "city": "Chennai"
}
Enter fullscreen mode Exit fullscreen mode

Access values like this:

print(person["name"])  # "Alice"
Enter fullscreen mode Exit fullscreen mode

Add or change values:

person["job"] = "Developer"
Enter fullscreen mode Exit fullscreen mode

Loop over keys and values:

for key, value in person.items():
    print(key, "β†’", value)
Enter fullscreen mode Exit fullscreen mode

🧠 Why it matters:

Use dictionaries when names, not positions, are important β€” like in a user profile or a config file.


5. 🀯 Bonus: Nesting β€” Lists Inside Dictionaries, and More

You can mix them:

student = {
    "name": "Karthik",
    "marks": [85, 90, 92]
}

average = sum(student["marks"]) / len(student["marks"])
print(student["name"], "has average:", average)
Enter fullscreen mode Exit fullscreen mode

🧠 Why it matters:

You can model real-world structures in your code. This is how you move toward real applications.


βœ… Summary: What You Learned in 003

Concept What You Can Do
return Make functions give back values
list Store and process groups of values
List tools Use built-ins like sum(), sort(), etc.
dict Store values with named keys
Nesting Combine data types to model real scenarios

Top comments (0)