Python Fundamentals ☕️
Tags: python, codenewbie, webdev, beginners
Published: 2020-12-15 19:04:45

Python is one of the most famous programming language in 2020, it is widely used for machine learning, data analysis, scripting and much more.

In order to improve as a developer and add a new skill to my tool belt, I decided to start learning Python. It is so exciting to begin this journey with you.

I love to share about my work and programming in general and can't wait to hear your feedbacks! 🔥

<h2>Table of Contents </h2> 
<ol>
   <li><a href="#variables">Variables</a></li>
   <li><a href="#logic">Arithmetic, Comparison & Logical Operators</a></li>
   <li><a href="#condition">Control Flow</a></li>
   <li><a href="#lists">Lists</a></li>
   <li><a href="#loop">Loops</a></li>
   <li><a href="#fun">Functions</a></li>
   <li><a href="#conclusion">Conclusion</a></li>
</ol>

<h3 id="variables">Variables</h3>

Variables are used to store data, they give developers the possibility to reuse and manipulate data in a program.

Naming conventions differ from one language to another. When writing Python code, you should name your variables as following.

✅ Comprehensive and specific name
✅ Lower case (❗️ constants should be upper case)
✅ Words separated with underscores

Example:
```python
username = "John"
number_input = 25
PI = 3.14
```

The scope is also important to mention. A variable is only accessible within the context it is declared in.

Example:
```python
# Declared in the global context
API_KEY = "ABCDEF1234"

def demo():
   # It works fine.
   print(API_KEY)

   # Declared in local context
   SECRET_STRING = "Something secret"

# It won't work. (Undefined variable: 'SECRET_STRING')
print(SECRET_STRING)
```

It might not be obvious but under the hood, every variable as a type. Primitives data types are Boolean, Integer, Float and String.

You have the possibility to convert a variable to another like this:

```python
# Integer
number = 5

# Float (5 => 5.0) 
number_to_float = float(number)

# String (5.0 => '5.0')
float_to_string = str(number_to_float)
```

<h3 id="logic">Arithmetic, Comparison & Logical Operators</h3>

Now that we are able to store data, let's use it! In this section, we will have a look to data manipulation and comparison.

It is pretty easy to perform math operations in Python. This might sound surprising, but it does work with numbers, strings and lists 🤯

```python
first_number = 2
second_number = 5

# 2 + 5 => 7
number_result = first_number + second_number 

first_word = "Hello"
second_word = "World!"

# "Hello" + "World!" => "HelloWorld!".
string_result = first_word + second_word 
```

Of course, there is a lot more to learn about that topic since you can perform subtraction, division, multiplication, ...

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v3vre6h4g154e2h64emv.png)

It is also possible to compare variables. This will make sense during the next section where we start working with conditions.

```python
# True
number_number = 5 == 5

# False
number_string = 5 == '5'

# True
greater = 5 > 3

# True
not_equal = 5 != '5'
```

Once again, there is a lot more to do with comparison operators, but it is enough to introduce that topic.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vwq42z9wjdn73gzwxdms.png)

Finally, it is possible to combine multiple comparisons with logical operators.

Example:
```python
age = 25
gender = 'Male'

#True (both expressions are true).
is_adult_or_girl = (age > 18) or (gender == 'Female')

#True (both expressions are true).
is_adult_boy = (age > 18) and (gender == 'Male')
```

At the end of the day, logical operators answer a question we ask with *True* or *False* depending on what operator we used.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ymu325yw96y85y0r6xhz.png) 

<h3 id="condition">Control Flow</h3>

This is probably *THE* very first thing that comes to my mind when speaking about programming, conditions and "if" statements.

*If* something is true, do this... *else* do that...
Hopefully, Python syntax is pretty easy to work with:

```python
age = 25

if age > 18:
   # We will end down here.
   print("You can buy alcohol")
else:
   print("You can buy Pepsi")
```

As you can see, it is pretty straightforward! If needed there is the 'elif' statement that lets you add more possibilities to your program.

There is a way to enhance the syntax a bit by using the ternary operator as follows:

```python
first = 5
second = 8

# Display "Second".
print("First") if first > second else print("Second")
```

A little side note to notify that indentation is very important in the Python syntax since there is no code blocks like in JavaScript syntax.

<h3 id="lists">Lists</h3>

So far, we used primitives data types such as integer and strings. It was working just fine, but you might come across a situation where it would make sense to store multiple information at the same place.

Lists come to the rescue with a simple way to store collections of data and provides plenty of useful methods. Items in a lists are indexed, the first one starts at index 0. 

```python
people = ["John", "James", "Max"]

# Display "James".
print(people[1])

# Display "Max".
print(people[-1])

# Display ["John", "James"].
print(people[0:2])
```

It is very easy to find out how many items a list contains:

```python
fruits = ["Apple", "Banana", "Orange"]

# Result is 3.
len(fruits)

# It works for Strings too! Result is 5.
len("Hello")
```

Let's play around with lists and their items.

```python
fruits = ["Apple", "Banana", "Orange"]
people = ["John", "James", "Max"]

# Result is ["Apple", "Banana", "Orange", "John", "James", "Max"].
fruits_and_people = fruits + people

# Add an item. Result is ["Apple", "Banana", "Orange", "Lemon"].
fruits.append("Lemon")

# Remove an item. Result is ["John", "Max"].
people.remove("James")

# Clear the list. Result is [].
people.clear()

# Sort the list. Result is ["James", "John", "Max"].
people.sort()
```

There are other collections we can work with such as tuples and dictionnaries and I will definetly speak about those later 🤓

<h3 id="loop">Loops</h3>

We are slowly but surely going deeper into this incredibly powerful language. As a developer you hate repetitive tasks (yes you do, it is not a question). 

Lists are great but would you imagine yourself manually go through every item in order to extract or manipulate data? Hell no! 

By far the most common way of programmaticaly repeat a task is by using loops. Let's begin with "for" loops.

```python
people = ["John", "James", "Max"]

# Every person will be displayed in the console.
for person in people:
   print(person)

# Every character will be displayed. It works on Strings as well!
for character in "Something":
   print(character)

# "Hello" is displayed 5 times.
for n in range(5):
   print(character)

# "else" after a loop describe an execution that should occurs once the loop is finished.
else:
   print("Loop finished")
```

Now that "for" loops have no secret for you, let's move on and give "while" loops a try:

```python
# Infinite loop
while True:
   print("I will never stop!")

# This loop will run until current_count reaches 10.
current_count = 0

while current_count < 10:
   current_count += 1
```

Thanks to "break" and "continue" statements, you have full control over your loop execution.

```python
number_list = [1, 2, "Hello", 3]

# "Break" will stop the loop execution if it finds a string in the list.
for number in number_list:
   if type(number) is str:
      break

   print("This list is full of numbers!") 

# "Continue" will ignore what comes next and jump to the next loop iteration.
for number in number_list:
   if type(number) is str:
      number_list.remove(number)
      continue

   print(f"{number} is not a string!")

```

<h3 id="fun">Functions</h3>

We are almost done with this introduction to Python's fundamentals! This is the last topic I am going to cover and you should be able to work with functions really quick 🌟

Functions are reusable blocks of code that only executes when they are asked to do so. You can define a new function with the "def" keyword.

```python
def print_hello():
   print("Hello!")

# Here I ask the function to execute and the result is displayed in the console.
print_hello()
```

When defining a function, you can pass in parameters to work with just like this:

```python
def add_numbers(num1, num2):
   print(num1 + num2)

# Here we call our function with two arguments and print the result.
add_numbers(5, 3)
```

Sometimes, printing the result is not enough and we want to store the result of the logic inside a function. In that case, we use the "return" keyword.

```python
def multiply_numbers(num1, num2):
   return num1 * num2

# Now the variable 'answer' holds the value returned by our function.
answer = multiply_numbers(5, 3)
```

Less common but still interesting to mention, you can accept as many arguments as you want with '*'.

```python
def print_args(*args):
   for arg in args:
      print(arg)

# It will print every argument we pass in the function
print_args(1, 2, 3, 4)
```

Optionally, it is possible to assign a default value to function parameters. If you do so, it is not anymore necessary to pass a value for a given parameter when you call the function.

```python
def default_params(num1 = 5, num2 = 3):
   return num1 + num2

# "answer" is equal to 15.
answer = default_params()
```

Last but not least, lambda functions are small anonymous functions that can only handle one expression.

```python
# This single line function takes one argument and returns it.
lambda_function = lambda arg: return arg
```

Lambda functions might seem confusing at this point but it will make sense later when we get the chance to work with functions inside of functions.

<h3 id="conclusion">Conclusion</h3>

It was a lot of fun to dive in this ocean of possibilities that Python offers! I hope you enjoyed reading, please share your thoughts and feedbacks in the comment section 👇