♦ πŸ† 2 min, 🐌 5 min

🐍 Python: Basics

So far we covered print(). But surprise surprise there's more than python can do πŸ™‚ Make sure to run the examples if you're not familiar with python.

Let's first check the basic data structure.

⚑ Basic data structures

String:

a: str = "a"
a = "a"

The above two are the same. Data structures don't have to be defined in python. Although it's good practice to define them when you can.

The : str part and other data type specifications are not necessary, but allow the IDE like PyCharm to catch any potential data structure errors in "real-time". C++ has a compiler for this and python doesn't so use type definitions whenever possible. You'll thank me later πŸ˜‰

List or array of values (index counting stats with 0 in python):

b: list = [0, 1, 2, 3]

  • Get zeroth element: b[0]
  • Sssign element 1: b[1] = 3
  • Get part of the list: b[0:2] from element 0 to element 2.

Key, value data structure named dict or dictionary:

c: dict = {"a": 1, 2: "b", "c": "d"}

  • To get an element: c["a"] or c[2] Yes a number can be a key.
  • To set an element: c["c"] = [0, 1, 2]

Yes you can nest data structures as much as you want in python really easily. Super powerful, but also fucking dangerous once your program grows ...

An int and float:

d: int = 10
e: float = 10.4

float in python actually has double precision (so it's a C double). There's no float in python standard. Some libraries like numpy have the option to specify the float data type.

bool is bool with True and False value:

f: bool = True

A set of numbers (or any other data structure) is called tuple:

d: tuple = (1, 2)

  • To get part of the tuple: d[1]

What about element assignment in tuple?: d[1] = 2 gives us an error 'tuple' object does not support item assignment. If you need to change the tuple, you need to create a new one. This is by design πŸ™‚

⚑ loops

There are also while and do loops but for is, in my opinion, more than enough (for most of the cases).

Print numbers from 0 to 9:

for i in range(10):
print(i)

To loop over every element of the list:

my_list = [1, 2, 3]

for element in my_list:
print(element)

Sometimes you want to loop over index and element at the same time. This is where enumerate comes in handy:

for i, element in enumerate(my_list):
print(i, element)

Or if you want to loop over a list in a single line and perform an operation you can use something called list comprehension:

my_list = [el*el for el in my_list]

Or to create a list of ten zeros with list comprehension:

a = [0 for _ in range(10)]

_ denotes that you don't care about the index so python will save on execution time and just "repeat" the command n = 10 times and save the result to the consecutive position in the array.

To loop over a dictionary you need to call method .items() on your dict c:

c = {"a": 1, "b": 2, "c": "d"} 

for key, value in c.items():
print(key, value)

To also get the index while you loop use the enumerate:

for i, (key, value) in enumerate(c.items()):
print(i, key, value)

Then sometimes with dictionaries, we want to loop over only keys or values of the dict:

for key in c.keys():
print(key)

for value in c.values():
print(value)

Next functions. Stuff that allows program modularity.

⚑ functions

To define a python function with no arguments through function definition:

def my_function():
return 1

Or with lambda:

my_function = lambda _: return 1

_ stands for no parameters. You then call your function with:

my_function()

Above definitions are the same.

And for a function with parameters:

def my_function(x):
return x*x

and lambda with parameters:

my_function = lambda x: return x*x

Use of lambda functions is actually discouraged in python but every now and then they come in super handy.

You can specify the return type of the function and types of input parameters as well:

def my_function(x: float) -> float:
return x*x

Encouraged practice πŸ˜‰

⚑ custom objects

Since python is an object-oriented language, we can create custom objects or classes πŸ™‚

To write a person class:

class Person:
name = ""


def __init__(self, name, city):
self.name = name
self.city = city

def __str__(self):
return f"{self.name}: {self.city}"

To create the object of type Person:

visitor = Person(name="Ziga", city="Ljubljana")

Person(name="Ziga", city="Ljubljana") is called a constructor and calls the method __init__(self, name, city) to actually create an instance of the object Person.

To access now the name of the visitor you can now do:

print(visitor.name)
print(visitor.city)

Or if you want to print the "whole" object, you can define the __str__(self) function in your custom class. Once print command is called on the object Person the __str__ command will be executed:

print(visitor)

outputs: Ziga: Ljubljana.

If you have custom objects, you can also use them to define the data type of the variable:

visitor: Person = Person(name="Ziga", city="Ljubljana")

Is that it?

Hell no. python has so much more features, but above should be more than enough to get started.

🐍 Python series:

Get notified & read regularly πŸ‘‡