4Geeks logo
4Geeks logo

Bootcamps

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Academy

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Search from all Lessons


LoginGet Started
← Back to Lessons

Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge

Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
  • learn to code

  • Python

Edit on Github

Learning to code with Python

Why Python?
Controlling Your Code's Flow
  • If…else…

Why Python?

Python is the first language you should learn, but obviously not the only one.

  • MIT decided to teach Python as the first language because its syntax prevents many errors, especially because it uses indentation instead of semicolons.

Variables

Click here to open the demo in another window

A variable is a container in which you can store any data. For example, you can have the following variable:

1age = 24

variables

With almost any programming language, you can create as many variables as you want or need. To start, in Python, you must declare the name of that variable with a unique name (relative to the value or what it receives)

The variable name is the most effective way to describe the content of a variable, use it wisely. It is important to choose a name that clearly indicates to you and other programmers what data is being stored in the variable. If you choose a bad or ambiguous name, your code will be almost impossible to understand, making it unusable. For example, let's change the name of our variable "age" to "a":

1a = 24

As you can see, the new variable name doesn't tell us anything about the data being stored and why it's being used.

Choosing the name of your variable is very important, so please don't use generic names. Be descriptive! A vague name will make it difficult to understand the purpose of the variable, especially for other programmers (including yourself).

Assigning a Value to Variables

As developers, we can set the value of a variable using the = operator. You don't have to set the value of a variable when you declare it for the first time. You can set or reset (overwrite) the value as many times as you want and whenever you want. The value is always the last one you set. Here are some examples of how to set values to variables:

1a = 24 2a = 25 3a = 80

The values of variables can change over time. To retrieve the value of a variable, you can print its value on the screen at any time. Every programming language has its own methods for printing. In Python, we use print.

Loading...

Data Types

Variables can have different types of values:

Data-TypePossible ValuesDescription
BooleanoTrue | FalseBooleans are intended for logical operations. If you ask a computer something like, "Is X equal to 3?" it will respond with a boolean (true or false).
StringAny string of charactersStrings are the only way we have to store words (sequences of characters). Note: strings must be enclosed in quotes.
NumberNumbers onlyIntegers, negative numbers, decimals, floats, etc. All possible types of numbers.
UndefinedEmptyWhen a variable has no assigned value, it remains undefined.
ArrayA list with any type of value.A sequence of any type of values. They can be mixed types of values; for example: [2, 3, 'Word', 2, 1, null, 232, 5, 3, 23, 234, 5, 'hello'].
ObjectsAny objectYou can create your own data types with more complex operations. We will talk more about this later.
NullOnly NullUsed to specify when the database or any other function does not return anything.
Loading...

Operations

What operations can I perform with variables? Depending on the data type, you have some different possibilities:

  • Numbers are easy - you can perform any mathematical operation you want.
  • Strings can be concatenated (merged), split, converted to uppercase or lowercase, etc.
  • Not much can be done with null, boolean, and undefined data types.
  • We will talk about Arrays and Objects in another section. They require much more attention.

Functions

Functions are pieces of code that can be reused multiple times during runtime, regardless of their position in the code. There are hundreds of reasons to use functions, but here are the top 2:

  • Divide and conquer: it's always easier to break your problems into smaller problems. This will become your biggest challenge when solving complex problems. Functions will be your best tools for abstraction.
  • Reusability: any normal development will take at least 5,000 lines of code. It's redundant and inefficient to keep writing the same code over and over again.

Declaring a Function

To declare a function in Python, you start with the def keyword followed by the name you want to give to that function.

Then you specify the parameters (inputs) that the function will accept within parentheses.

Next, you start a new indented block of code where you write the code that your function should perform. Once you're done with the function's code, you simply stop the indentation.

Note: To return a value from the function, you use the return keyword followed by the value you want to return. You can place the return statement anywhere within the function's code block, and the function will exit and return that value.

Here is an example:

1def multiply(param1, param2): 2 result = param1 * param2 3 return result # This is how you return a value from the function

Function Parameters and Scope

The scope of a variable determines where that variable is available for use. There are two main types of scopes:

Local Variables

A local variable is only available within the scope of the nearest curly braces. For example, variables passed as parameters to functions are only available within the content of that specific function.

Global Variables

If you declare a variable at the beginning of your code, it will be available throughout the entire code, even within the content of any particular function.

Loading...

Logical Operations

Computers think in black or white. Everything is true or false. All decisions on a computer boil down to a simple boolean. You can prepare a computer to solve particular problems by writing code that asks the right questions to solve that problem.

For example, if I want a computer to give candy only to children older than 13 years old, I can tell the computer to ask.

Is this child's age greater than 13 years? Yes or no?

In python, you can ask the computer to do the following logical operations:

OperationSyntaxExamples
Equal to==Is 5 == 5? True!
Is 5 == 4? False!
Is 5 == '5'? True!
No Igual a!=Is 5 != 5? False!
Is 5 != '5'? False!
Is 1 != 'Hello'? True!
Greater than>Is 5 > 5? False!
Is 6 > 3? True!
Less than<Is 6 < 12? True
Greater or Equal>=Is 6 <= 6? True
Is 3 <= 6? True
Less or Equal<=You get the idea 🙂

To create really useful operations, you can combine multiple operations in the same question using AND, OR, and NOT (and, or, or not respectively).

You can group logical operations within parentheses and use nested parentheses to perform multiple operations at the same time.

OperationSyntaxExamples
ANDandWith AND, both sides MUST BE TRUE for everything to become true.
Is (5 == 5 and 3 > 1) true? True!
Is ('Ramon' == 'Pedro' and 2 == 2) false? False
ORorIs ('Oscar' != 'Maria' or 2 != 2) true? True!
Is (5 == '5' and 'Ramon' != 'Pedro') or (2 == 2) true? True!
NOTnotNOT will be exactly the opposite of the logical operator's result:
Is not (5 > 5) true? True!
Is not (True) false? False!

Controlling Your Code's Flow

Now is when things start to get fun! To control your application's flow, you have several options, and you'll use them every day. So, you should feel comfortable using them.

If…else…

The first tool you have is the if...else conditional. It's straightforward. You can tell the computer to skip any part of your code depending on the current value of your variables.

The if statement allows you to execute a block of code if certain conditions (or truths) are met. The "else" statement will execute an alternative block of code if the condition is false.

1if number < 18: 2 print("Hello"); 3else: 4 print("Good bye!")

Switch

Python does not have the ability to use switch statements like other languages (e.g., JavaScript, C#, etc.).

While

It is possible to loop a segment of your code as many times as you want or need. Loops are one of the most important tools for developers these days.

Imagine you're in an elevator: the elevator must loop through the floors until it reaches the specific floor you want.

A while loop will execute a block of code as long as a condition is true. Once the condition is false, the loop will stop executing the code.

1sum = 0; 2number = 1; 3while number <= 50: 4 sum += number 5 number += 1 6 7print("Sum = " + sum)

For Loop

For is similar to while, with the only difference being that you must specify the condition to stop from the start. For that reason, for is a bit more organized and easier to understand.

Note: when creating a loop, make sure the condition eventually becomes false to avoid an infinite loop. In an infinite loop, the code runs indefinitely and will freeze your browser.

1for i in range(10): 2 print("This is number" + " " + i) 3

For...In

For...in loops can be used to iterate over the properties of an object. Inside the parentheses, you can set any name to represent the information within the object and then include the name of the object:

1for (variable in object)<br> { 2code block to be executed 3}
1dog = { 2 "species": "Great Dane", 3 "size": "Extra Large", 4 "age": 3 , 5 "name": "Rocky" 6} 7 8for items in dog: 9 print(dog[items]) 10

So... tell me, did you enjoy programming?

Programming is like Taco Bell: the same ingredients are always used, but they are mixed in different ways. You know how to write code, but... do you know how to solve real-world problems?