16
Everything you need to know to get started with Python
First of all, all the concepts that I'm going to show you are almost the same for basically any modern programming language. That's because all programming languages have variables and loops, for example. It is more like programming logic than a "Python tutorial". I hope you enjoy and carry that knowledge throughout your whole career.
In this article, I'll explain everything you need to know to get started with Python.
The simplest program the we could write is the "Hello world" program.
# file: hello.py
print("Hello, world!")
The print()
will output to the screen whatever is inside of the parenthesis and between quotes. Above print()
we have a #
followed by something, everytime we see this #
in Python, we say it is a comment. Every comment is ignored by the Python interpreter.
To execute this code, it will depend on the operating system you are using. If you are using Linux, you can type in the command-line python hello.py
.
Imagine a situation where you want to describe a person using Python. For example, you want to print the name, age, hobbies and much more. For that, we could write the code below:
print("Joseph is a boy who likes Python")
print("Joseph is 18 years-old")
print("Joseph likes to play video games")
print("Joseph is a Computer Science student")
If you run this code, everything just works fine. But, there is room for improvements. And if we could store the name of Joseph somewhere, so we can reuse it later without needing to type "Joseph" everytime, is there any way to do that? YEAH! That's why variables exist.
Variables are like placeholders for values, just like in Math.
name = "Joseph" # That's how we declare a variable in Python
print(name, "is a boy who likes Python")
print(name, "is 18 years-old")
print(name, "likes to play video games")
print(name, "is a Computer Science student")
Now, we can use variable name
anywhere. There is no need to write by hand the name "Joseph".
See more examples on variables:
age = 18 # int (integer)
wallet = 18.50 # float (floating point numbers)
name = "Joseph" # String (Collection of characters)
can_vote = True # Boolean (Boolean can be two things: True or False)
imaginary_number = 1j # Complex
Sometimes you want to make decisions in your program based on some kind of situation. In that case, you want to use conditionals statements, like if
, else if
and else
.
For the sake of a better understanding, let's write a program that receives an integer representing the age
and check if
you can vote based on your age
. The most common voting age at Brazil is 18. So we need to check if the received integer is greater than or equal to 18.
age = 19
if age >= 18:
print("You can vote!")
else:
print("You can not vote!")
The line below if age >= 18
will just be executed if the condidition age >= 18
is True. In this example above, the program will print out to the screen "You can vote!" because age = 19 and 19 is greater than 18, which means the if
is True, that's why it is gonna be executed instead of else
. else
is just executed when the conditions above him are false. If age was equal to 17, else
would be executed because age >= 18
is False.
Sometimes you want to check more conditions. That's why we use elif
. Let's write a program to check your grade.
grade = "A"
if grade == "A":
print("Awesome!")
elif grade == "B":
print("Good")
elif grade == "C":
print("Not so good")
else:
print("Bad")
Using elif
, we can check more than one condition and we use else
without a condition because it will only be executed if and only if every condition above is false. In this example, the program will print out "Awesome!" because the first condition if grade == "A"
is True and the program will just finish after it.
Always remember this structure below:
if something_is_true:
# Execute this
elif something_is_true:
# Execute this
else:
# Execute this if and only if every condition above is false
That is everything you need to understand about conditionals for now. I recommend you to start writing simple programs and articulate your logic using if
, elif
and else
when you need it. If you want to solve some programming puzzles, try this website here.
We already learned about variables and conditional statements, so far so good. Now it is time to learn about lists.
Imagine a situation where you want to store a lot of different colors somewhere. The first thing you might do is the following:
first_color = "Red"
second_color = "Green"
third_color = "Blue"
You could do that, but try to imagine how terrible would be if you want to store 10, 20 or 30 differents colors. Is there a way to create some sorta of list where I can insert and access it later in my program? Yep, Python has lists.
- What is a list?
List are data structures used to store data sequentially.
my_list = [] # That's how you declare an empty list
colors = ["Red", "Green", "Blue"] # Declaring and defining the elements of a list
- Operations in list
I'm going to be explaining a few common operations that you might want to perform using lists. Of course, there are a lot of them and you can google as you need it.
- Accessing elements using indices
colors = ["Red", "Green", "Blue"] # Declaring and defining the elements of a list
print(colors[0]) # Output: Red
print(colors[1]) # Output: Blue
We can access an element in the list using list[] notation. The first element always starts at the index 0, that's why when we use colors[0]
we get "Red" as the output, why? it's the first element of the list.
- Insert elements at the end
Instead of writing the data directly in the list, we can insert elements during the execution of the program using append()
.
colors = [] # Empty list
colors.append("Red") # colors = ["Red"]
colors.append("Blue") # colors = ["Red", "Blue"]
- Find the size of the list
numbers = [2, 3, -1, 20]
size = len(numbers) # size = 4
- Delete some element and last element
numbers = [2, 3, -1, 20]
# Deleting element from the end of the array
numbers.pop() # numbers = [2, 3, -1]
# Deleting element at the index 1
numbers.pop(1) # numbers = [2, -1]
- Remove ONLY first occurence of a particular element
fruits = ["apple", "banana", "cherry", "apple"]
fruits.remove("apple") # fruits = ["banana", "cherry", "apple"]
- Remove all elements of a list
fruits = ["apple", "banana", "cherry", "apple"]
fruits.clear() # fruits = []
- Sort the list
numbers = [2, 3, -1, 20]
numbers.sort() # numbers = [-1, 2, 3, 20]
numbers.sort(reverse = True) # numbers = [20, 3, 2, -1]
If you want to store the sorted list in another list, you might want to use sorted()
rather than sort()
.
numbers = [2, 3, -1, 20]
sorted_numbers = sorted(numbers) # sorted_numbers = [-1, 2, 3, 20]
Now it is time to learn more about strings. More? Did we already learn something about strings? Yes, we are dealing with strings since the beginning of this articles.
- What is a string?
String is a sequence of Unicode characters. Basically, in Python, anything between quotes is a string, for example "This is a string" is a string because it is between quotes.
You can think that a string is a list of characters. We can access any character in the string using indexing.
fact = "Python is awesome!"
print(fact) # "Python is awesome!"
print(type(fact)) # <class 'str'> ('str' means 'string')
print(fact[0]) # P
print(fact[-1]) # !
You can use negative numbers to get characters from the end, -1 will return the last character or element of the list
Operations with string
Capitalize string
country = "brazil"
country = country.capitalize() # Brazil
- String to uppercase or lowercase
country = "brazil"
country = country.upper() # BRAZIL
country = country.lower() # brazil
- Check if string ends with certain characters or another string
This method returns a boolean (True or False), so you can easily use it a if
condition.
fact = "Python is awesome!"
if fact.endswith("awesome!"):
print("Yes, it ends with 'awesome!'")
- Replace some character / substring by another character / substring
fact = "Python is awesome!"
if fact.endswith("awesome!"):
fact.replace("awesome", "terrific") # Now, fact is "Python is terrific!"
- Transform string into a list
You can separate a string into a list based on certain character or substring.
names = "Jack, Zoe, Mike, John, Gabriel"
names = names.split(", ") # ["Jack", "Zoe", "Mike", "John", "Gabriel"]
So, basically, everytime we see ", " in the string, we're gonna split it. By default, split()
split the string using the space.
- Check if string's characters are all lowercase / uppercase
country = "usa"
if country.islower():
country = country.upper() # USA
if country.isupper():
country = country.lower() # usa
Imagine the situation where if you want store informations about yourself in your program, such as name, age, phone number and more. You can think about using a list for that.
info = ["Hicaro", 18, 232838131912-1]
print("My name is", info[0])
You could that easily, but maybe it is not the best option. If your code base was too big, you would have scroll up and down everytime you want to know what is stored in the index 0 of the info
list. It is bad design. What should I do that? Basically, when you want to map something to another thing, we're gonna be using a Dictionary.
- What is a dictionary?
A dictionary is a data structure based on key-value pairs. We always have a key that we use to access some specific value in memory.
info = {} # Empty dictionary
info["Name"] = "Hicaro"
info["Age"] = 18
info["Tel"] = 232838131912-1
if info["Name"] == "Hicaro":
print("My name is", info["Name"])
Instead of inserting each key-value pair one by one like I did above, you could create the dictionary directly inside the {}
.
info = {"Name": "Hicaro", "Age": 18, "Tel": 232838131912-1}
if info["Name"] == "Hicaro":
print("My name is", info["Name"])
The key doesn't need to be a string, you can use numbers as always, but you can not use lists as dict key.
Now you have something way more sofisticated to store data and efficient in terms of time for accessing data. Now, we don't have the problem of not knowing about what the index because the "index" will be basically the key that we choose. Pretty sure info["Name"]
is more readable than info[0]
.
Let's bring a lot of concepts together. Imagine you have a list of friends's name and you want to print "Hello" to all of them. How would do that? You could make a print statement for each one of them.
friends_name = ["Laurie", "Erlich", "Gilfoyle", "Richard", "Monica"]
print("Hello, ", friends_name[0])
print("Hello, ", friends_name[1])
print("Hello, ", friends_name[2])
print("Hello, ", friends_name[3])
print("Hello, ", friends_name[4])
It is kinda of exhaustive and repetitive. Probably everytime you're doing something that is so much repetitive in programming, there will be a better solution for that. In fact, there is one. We just want to repeat basically the same print()
for each friend repetitively, that's why we use a loop. We have two options for looping (for
and while
). We use for
when we want to iterate over a sequence (it is not a rule, you can use anything you want) and while
when we want to repetitively do a thing while something is true.
friends_name = ["Laurie", "Erlich", "Gilfoyle", "Richard", "Monica"]
for name in friends_name:
print("Hello, ", name)
We can easily iterate over a sequence using for
because we can use in
. name
is basically a variable that represents an element of the list, starting from the first to the last element. This loop will stop when we iterate over the whole list.
If you want know more about loops, W3Schools articles about loops certainly do a better job explaining to you these concepts.
Now we have functions. Functions are blocks of code that we can use to execute in just one line of code. For example:
def my_function_name():
print("Printing something from function")
my_function_name() # Printing something from function
In the code above, I create a function using def
, after that I gave a name for my function (my_function_name
) so I can access it (just like we do with variables and list), after that I use ()
(I'll explain it later). Below the definition, I defined the body of the function, the block of code that we want to execute. In the last of code, we are calling the function using my_function_name()
and then it will execute the function. See more examples:
def sum(number):
print(number + 3)
sum(2) # 5
Notice that I put a parameter inside of the parentheses, that's because when I call the function in the last line of code, I put 2 there, so the parameter number
will equal to 2 and then we will print 2 + 3
which is 5.
And if you try execute this function inside a variable?
my_sum = sum(2) # None
We'll get None
and not 5, why? Because we are not returning anything from the function, if you want to return
the sum and store it in the variable my_sum
, we should use the return
keyword.
def sum(number):
return number + 3
my_sum = sum(2) # 5
If you have something to suggest, please leave it in the comments below.
Don't forget to start doing projects and learn the language as you build. At the end of the day, you don't need to know all this functions and methods, you need to know where to find it and use it as you need. Good luck and thank you for the attention, I hope you learned something new with this article, see ya next time ❤️
16