DEV Community

Avnish
Avnish

Posted on

Learning Python - A Beginner's Guide

Here’s a well-structured and easy-to-understand version of your article, along with step-by-step explanations and example code snippets to help clarify the concepts.


Python Basics: A Beginner's Guide

1. Variables

Variables are containers for storing data. Think of them as labels for your data. In Python, defining a variable is straightforward.

# Assigning values to variables
one = 1
two = 2
some_number = 10000

# Different data types
true_boolean = True   # Boolean
my_name = "John Doe"  # String
book_price = 15.80    # Float
Enter fullscreen mode Exit fullscreen mode

Each variable stores a value that can be retrieved or updated.


2. Control Flow: Conditional Statements

Control flow allows your program to make decisions. Python uses if, elif, and else for conditional logic.

# Example: Using if
if 2 > 1:
    print("2 is greater than 1")

# Example: Using if-else
if 1 > 2:
    print("1 is greater than 2")
else:
    print("1 is not greater than 2")

# Example: Using if-elif-else
if 1 > 2:
    print("1 is greater than 2")
elif 2 > 1:
    print("2 is greater than 1")
else:
    print("Both are equal")
Enter fullscreen mode Exit fullscreen mode

3. Loops

Loops are used for iterating over sequences or repeating operations.

While Loop

The while loop repeats a block of code as long as the condition is True.

num = 1
while num <= 5:
    print(num)
    num += 1  # Increment the value of num
Enter fullscreen mode Exit fullscreen mode

For Loop

The for loop iterates over a sequence like a list or range.

# Using range
for i in range(1, 6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

4. Lists

Lists are used to store multiple items in a single variable.

# Creating a list
my_list = [10, 20, 30, 40]

# Accessing elements using indices
print(my_list[0])  # Output: 10
print(my_list[2])  # Output: 30

# Adding elements
my_list.append(50)
print(my_list)  # Output: [10, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

5. Dictionaries

Dictionaries store data in key-value pairs.

# Creating a dictionary
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Accessing values using keys
print(person["name"])  # Output: Alice

# Adding a new key-value pair
person["job"] = "Engineer"
print(person)
Enter fullscreen mode Exit fullscreen mode

6. Iterating Through Data Structures

Iterating Through Lists

my_books = ["Book A", "Book B", "Book C"]
for book in my_books:
    print(book)
Enter fullscreen mode Exit fullscreen mode

Iterating Through Dictionaries

# Using keys and values
for key, value in person.items():
    print(f"{key}: {value}")
Enter fullscreen mode Exit fullscreen mode

7. Classes and Objects

Classes define blueprints for creating objects.

# Defining a class
class Vehicle:
    def __init__(self, wheels, fuel, max_speed):
        self.wheels = wheels
        self.fuel = fuel
        self.max_speed = max_speed

# Creating an object
my_car = Vehicle(4, "electric", 150)
print(my_car.wheels)  # Output: 4
Enter fullscreen mode Exit fullscreen mode

8. Encapsulation

Encapsulation hides internal data, exposing only the necessary parts.

class Person:
    def __init__(self, name, age):
        self._name = name  # Non-public variable
        self._age = age

    def get_name(self):  # Public method
        return self._name

    def set_name(self, name):
        self._name = name
Enter fullscreen mode Exit fullscreen mode

9. Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

# Child class inheriting from Animal
class Dog(Animal):
    def speak(self):
        print(f"{self.name} barks")

my_dog = Dog("Buddy")
my_dog.speak()  # Output: Buddy barks
Enter fullscreen mode Exit fullscreen mode

Summary

  • Variables: Containers for data.
  • Control Flow: Use if, elif, and else for decisions.
  • Loops: Use for and while to repeat actions.
  • Lists: Store multiple values in an ordered sequence.
  • Dictionaries: Store key-value pairs for flexible data storage.
  • Classes & Objects: Model real-world entities.
  • Encapsulation: Protect internal data.
  • Inheritance: Reuse attributes and methods in derived classes.

With these basics, you're ready to start building Python programs! 🚀

Top comments (0)