Darekdari / Python Basics

Python Basics: Array, Break, Class, Dataclass & Datetime

Python is a high-level, interpreted, general-purpose language used for web development, data analysis, machine learning and more, and it is one of the easiest languages to learn. This guide covers five fundamentals. Every one has a short explanation, working code and a live demo you can play with.

Beginner friendly5 live demosCopy-paste codePython 3.7+
01 / Array

Python Array: Store Numbers of One Type

The array module gives you a homogeneous array: every element must have the same data type. Import the module first, then call array.array() with two arguments: a type code ('i' means signed integer) and the starting values.

Create and looparray.py
import array

# create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])

# print the array
for i in arr:
    print(i)

Add and remove elements

append() adds to the end and insert() adds at a position. To take elements out, use pop() (by index) or remove() (by value).

Change the arrayarray.py
# append an element to the array
arr.append(6)

# insert 7 at index 3
arr.insert(3, 7)

# remove the last element
arr.pop()

Read, change and measure

An array with n elements has indexes 0 to n-1. Negative indexes count from the end, so -1 is the last element. Assign to an index to change a value, and use len() for the length.

Index, assign, lenarray.py
arr = array.array('i', [1, 2, 3, 7, 4, 5, 6])

print(arr[0])    # Output: 1
print(arr[3])    # Output: 7
print(arr[-1])   # Output: 6 (last element)

arr[2] = 8       # modify the value of an element
print(len(arr))  # Output: 7
Fixed: the original post printed 6 for len(arr), but after one append() and one insert() the array holds 7 elements. It also said append() and insert() remove elements; they only add.
Live demo

Array playground

-5
1
0
-4
2
1
-3
3
2
-2
4
3
-1
5
4
>>> Pick a button. Try index -1 or an index that is too big.
5len(arr)
15sum(arr)
02 / Break

Python Break: Stop a Loop Early

The break statement ends the nearest for or while loop at once. Python then runs the first statement after the loop. Use it when a condition tells you there is nothing left to do.

break in a while loopbreak.py
i = 0
while i < 10:
    print(i)
    i += 1
    if i == 5:
        break

# Output: 0 1 2 3 4

Here i is increased before the check, so the loop stops after printing 4.

break in a for loopbreak.py
for i in range(10):
    print(i)
    if i == 5:
        break

# Output: 0 1 2 3 4 5

In the for loop the value is printed before the check, so 5 is printed. Same stop value, different output. Try it below.

Live demo

Where does the loop stop?

Press “Run the loop”.
03 / Class

Python Class: A Blueprint for Objects

A class is a blueprint for building objects that have properties (attributes) and actions (methods). You define one with the class keyword, a name, and an indented block.

Define a classperson.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
  • __init__() is the constructor. Python calls it when you create an object, and it sets the starting values.
  • self is the object itself. self.name is that object’s own name.
  • say_hello() is a method that uses the object’s data to print a message.

Create an object by calling the class name like a function, then use dot notation to reach its attributes and methods.

Create and use an objectperson.py
person1 = Person("John", 25)

print(person1.name)   # Output: John
print(person1.age)    # Output: 25
person1.say_hello()   # Output: Hello, my name is John and I'm 25 years old.
Live demo

Build your own Person

Create an object and watch the code run.
04 / Dataclass

Python Dataclass: Less Code for Data Classes

A data class is a class that mostly stores data. The @dataclass decorator comes from the dataclasses module (Python 3.7 and later). You list the fields with type annotations, and Python generates __init__(), __repr__() and __eq__() for you.

Define a dataclassperson_dc.py
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

person1 = Person("John", 25)

print(person1.name)   # Output: John
print(person1.age)    # Output: 25
print(person1)        # Output: Person(name='John', age=25)
Why use it: the same four-line class replaces the whole constructor, a readable print() output and value comparison. On Python older than 3.7 you must write those methods by hand.
Live demo

Regular class vs dataclass

Edit two people. See how print() and == behave in each kind of class.

Regular class

@dataclass

05 / Datetime

Python Datetime: Work With Dates and Times

The datetime module has classes for dates, times and both together. You can read each part with year, month, day, hour, minute, second and microsecond.

Dates, times, nowdates.py
import datetime

d = datetime.date(2023, 4, 19)
print(d)    # Output: 2023-04-19

t = datetime.time(12, 30, 15)
print(t)    # Output: 12:30:15

dt = datetime.datetime(2023, 4, 19, 12, 30, 15)
print(dt)   # Output: 2023-04-19 12:30:15

now = datetime.datetime.now()
print(now)  # Output: 2023-04-19 13:45:23.491405 (your current time)

Subtract two datetimes

Subtracting one datetime from another gives a timedelta: the length of time between them.

timedeltadates.py
import datetime

dt1 = datetime.datetime(2023, 4, 19, 12, 30, 15)
dt2 = datetime.datetime(2023, 4, 18, 10, 15, 30)

delta = dt1 - dt2
print(delta)  # Output: 1 day, 2:14:45
Live demo

timedelta calculator

1delta.days
8085delta.seconds
94485total_seconds()
Quick quiz

Test What You Learned

Turn on JavaScript to take the quiz.

FAQ

Frequently Asked Questions About Python Basics

What is the difference between a Python array and a list?

An array from the array module stores one data type and uses less memory. A list can hold mixed types and is used far more often. Choose an array when you need compact, same-type numbers.

What does break do in Python?

break ends the nearest enclosing for or while loop immediately. The program continues with the first statement after the loop.

When should I use a dataclass instead of a normal class?

Use a dataclass when the class mainly stores data. The decorator generates __init__, __repr__ and __eq__, so you write far less code. Use a normal class when you need custom behavior in the constructor or many methods.

Which Python version do I need for dataclasses?

Python 3.7 or later. In older versions you must define the special methods yourself.

How do I find the difference between two dates?

Subtract one datetime from the other. The result is a timedelta with days, seconds and total_seconds().

Conclusion

Keep Practicing Python

You now know how to store numbers in an array, stop loops with break, model things with classes and dataclasses, and measure time with datetime. Change the demos’ values, then rebuild each example from memory. If this helped you, leave a comment and share the post.

Learn more

More info about us

Scroll to Top