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.
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.
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).
# 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.
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: 76 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.Array playground
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.
i = 0
while i < 10:
print(i)
i += 1
if i == 5:
break
# Output: 0 1 2 3 4Here i is increased before the check, so the loop stops after printing 4.
for i in range(10):
print(i)
if i == 5:
break
# Output: 0 1 2 3 4 5In the for loop the value is printed before the check, so 5 is printed. Same stop value, different output. Try it below.
Where does the loop stop?
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.
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.selfis the object itself.self.nameis 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.
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.Build your own Person
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.
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)print() output and value comparison. On Python older than 3.7 you must write those methods by hand.Regular class vs dataclass
Edit two people. See how print() and == behave in each kind of class.
Regular class
@dataclass
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.
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.
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:45timedelta calculator
Test What You Learned
Turn on JavaScript to take the quiz.
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().
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.
