Python Fundamentals ☕️

killianfrappartdev

Killian Frappart

Posted on December 15, 2020

Python Fundamentals ☕️

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! 🔥

Table of Contents

  1. Variables
  2. Arithmetic, Comparison & Logical Operators
  3. Control Flow
  4. Lists
  5. Loops
  6. Functions
  7. Conclusion

Variables

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:

username = "John"
number_input = 25
PI = 3.14
Enter fullscreen mode Exit fullscreen mode

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

Example:

# 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)
Enter fullscreen mode Exit fullscreen mode

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:

# Integer
number = 5

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

# String (5.0 => '5.0')
float_to_string = str(number_to_float)
Enter fullscreen mode Exit fullscreen mode

Arithmetic, Comparison & Logical Operators

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 🤯

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 
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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

# True
number_number = 5 == 5

# False
number_string = 5 == '5'

# True
greater = 5 > 3

# True
not_equal = 5 != '5'
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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

Example:

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')
Enter fullscreen mode Exit fullscreen mode

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

Control Flow

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:

age = 25

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

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:

first = 5
second = 8

# Display "Second".
print("First") if first > second else print("Second")
Enter fullscreen mode Exit fullscreen mode

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.

Lists

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.

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

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

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

# Display ["John", "James"].
print(people[0:2])
Enter fullscreen mode Exit fullscreen mode

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

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

# Result is 3.
len(fruits)

# It works for Strings too! Result is 5.
len("Hello")
Enter fullscreen mode Exit fullscreen mode

Let's play around with lists and their items.

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()
Enter fullscreen mode Exit fullscreen mode

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

Loops

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.

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")
Enter fullscreen mode Exit fullscreen mode

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

# 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
Enter fullscreen mode Exit fullscreen mode

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

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!")

Enter fullscreen mode Exit fullscreen mode

Functions

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.

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

# Here I ask the function to execute and the result is displayed in the console.
print_hello()
Enter fullscreen mode Exit fullscreen mode

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

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

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

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.

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

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

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

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)
Enter fullscreen mode Exit fullscreen mode

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.

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

# "answer" is equal to 15.
answer = default_params()
Enter fullscreen mode Exit fullscreen mode

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

# This single line function takes one argument and returns it.
lambda_function = lambda arg: return arg
Enter fullscreen mode Exit fullscreen mode

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.

Conclusion

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 👇

💖 💪 🙅 🚩
killianfrappartdev
Killian Frappart

Posted on December 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner To Pro - Python Learning Path
Python Fundamentals ☕️
python Python Fundamentals ☕️

December 15, 2020