Cristhian Villegas
Backend9 min read0 views

Python Course #2: Variables and Data Types in Python

Python Course #2: Variables and Data Types in Python

Introduction: What are variables?

Python Logo

Welcome to Part 2 of 10 of the Python Course from Scratch. In the previous article, we installed Python and wrote our first program. Now we are going to learn one of the most important concepts in programming: variables.

Imagine you have several labeled boxes on your desk. In a box labeled "age" you store the number 25. In another one labeled "name" you store the text "Maria". And in another labeled "has_account" you store a "yes" or "no". That is exactly what variables are in programming: named boxes where you store information.

The computer needs to store data in order to work with it. Variables are the mechanism it uses to do so. Without variables, you could not do almost anything useful in a program.

📌 Note: This article is Part 2 of 10 of the course. If you have not read Part 1 (Python installation), we recommend starting there.

Creating and assigning variables

In Python, creating a variable is very simple. You just need to write a name, the = sign, and the value you want to store:

python
1# Creating variables
2name = "Maria"
3age = 25
4height = 1.68
5is_student = True

That simple. You do not need to declare the data type or use special keywords. Python takes care of everything automatically.

The = sign in programming does not mean "is equal to" like in math. It means "store this value in this variable". Read it from right to left: "store the value 25 in the variable age".

Rules for naming variables

You cannot give a variable just any name. There are rules you must follow:

RuleValidInvalid
Only letters, numbers, and underscoresmy_name, age2my-name, my name
Cannot start with a numberdata11data
Cannot be a reserved wordmy_classclass, if, for
Case-sensitiveAge and age are different
💡 Tip: In Python, the convention is to use snake_case for variable names: all lowercase with words separated by underscores. Examples: full_name, birth_date, total_price.

You can change the value of a variable at any time:

python
1points = 10
2print(points)  # Shows: 10
3
4points = 25
5print(points)  # Shows: 25
6
7points = points + 5
8print(points)  # Shows: 30

Basic data types: int, float, str, bool

Every value you store in a variable has a data type. Python has four basic types that you will use constantly:

int (integers)

These are numbers without a decimal point. Used for counting things, ages, quantities, etc.

python
1age = 25
2quantity = 100
3temperature = -5
4year = 2025

float (decimal numbers)

These are numbers with a decimal point. Used for prices, measurements, percentages, etc.

python
1price = 19.99
2height = 1.75
3pi = 3.14159
4percentage = 85.5
⚠️ Note: In Python, the dot is used as the decimal separator, not the comma. Write 19.99, not 19,99.

str (text strings)

"str" stands for "string". These are pieces of text enclosed in quotes, either single or double:

python
1name = "Maria"
2last_name = 'Lopez'
3message = "Hello, welcome to the course"
4address = '123 Main Street'
5
6# You can also use triple quotes for multi-line text
7description = """This is text
8that spans multiple
9lines"""

bool (logical values)

"bool" stands for "boolean" (named after mathematician George Boole). It only has two possible values: True or False. Used to answer yes/no questions.

python
1is_adult = True
2has_discount = False
3is_raining = True
4course_completed = False
⚠️ Note: True and False must have their first letter capitalized. Writing true or false (lowercase) causes an error in Python.

The type() function: how to check a variable's type

If you ever need to know what data type a variable contains, you can use the type() function:

python
1name = "Maria"
2age = 25
3height = 1.68
4is_student = True
5
6print(type(name))        # <class 'str'>
7print(type(age))         # <class 'int'>
8print(type(height))      # <class 'float'>
9print(type(is_student))  # <class 'bool'>

The type() function tells you the "class" (type) of the value. It is very useful when you are learning or when something does not work as expected and you want to verify what data type you are using.

You can also use it directly with values:

python
1print(type(42))        # <class 'int'>
2print(type(3.14))      # <class 'float'>
3print(type("hello"))   # <class 'str'>
4print(type(True))      # <class 'bool'>

Type conversion (casting)

Sometimes you need to convert one data type into another. For example, converting the text "25" into the number 25 so you can do math operations. This is called casting (type conversion).

Python has functions to convert between types:

python
1# Convert to integer
2number = int("25")       # Converts the text "25" to the number 25
3print(number + 5)        # Shows: 30
4
5# Convert to decimal
6decimal = float("19.99") # Converts the text "19.99" to the number 19.99
7print(decimal)           # Shows: 19.99
8
9# Convert to text
10text = str(100)          # Converts the number 100 to the text "100"
11print("Your score is: " + text)  # Shows: Your score is: 100
12
13# Convert between int and float
14integer = int(3.7)       # Converts 3.7 to 3 (drops decimals, does NOT round)
15decimal = float(5)       # Converts 5 to 5.0
⚠️ Warning: You cannot convert just any text to a number. int("hello") causes an error because "hello" is not a number. You can only convert text that represents valid numbers.

When do you need casting? A very common case is when you read data from the user (we will see this later in this article). The input() function always returns text, so if you need a number, you must convert it:

python
1# Without casting - this does not work as expected
2age_text = "25"
3print(age_text + 5)  # ERROR: you cannot add text + number
4
5# With casting - this works
6age_number = int("25")
7print(age_number + 5)  # Shows: 30

Basic operations with numbers

Python can work as a calculator. Here are the math operations you can perform:

OperatorOperationExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.3333
//Floor division10 // 33
%Modulo (remainder)10 % 31
**Exponentiation2 ** 38

Let's see practical examples:

python
1# Basic operations
2print(15 + 8)      # 23
3print(20 - 7)      # 13
4print(6 * 4)       # 24
5print(15 / 4)      # 3.75
6
7# Floor division (discards the decimals)
8print(15 // 4)     # 3
9
10# Modulo (the remainder of the division)
11print(15 % 4)      # 3 (because 15 = 4*3 + 3)
12
13# Exponentiation
14print(2 ** 10)     # 1024 (2 raised to the power of 10)
15
16# You can use variables in operations
17price = 100
18discount = 15
19final_price = price - discount
20print(final_price)  # 85
21
22# You can combine operations
23result = (10 + 5) * 2
24print(result)       # 30
💡 Tip: Python follows the standard order of math operations (multiplication and division first, then addition and subtraction). Use parentheses () to control the order when needed.

Operations with strings (text)

Text also has its own operations. Let's look at the most useful ones:

Concatenation (joining text)

python
1first_name = "Maria"
2last_name = "Lopez"
3
4# Join text with +
5full_name = first_name + " " + last_name
6print(full_name)  # Maria Lopez

Repeating text

python
1line = "-" * 30
2print(line)  # ------------------------------
3
4laugh = "ha" * 5
5print(laugh)  # hahahahaha

Text length: len()

python
1message = "Hello World"
2print(len(message))  # 11 (counts all characters, including the space)

Slicing: getting parts of a text

You can extract parts of a text using square brackets []. Each character has a position (index) that starts from 0:

python
1text = "Python"
2#       P  y  t  h  o  n
3#       0  1  2  3  4  5
4
5print(text[0])     # P (first character)
6print(text[1])     # y (second character)
7print(text[-1])    # n (last character)
8
9# Get a range of characters [start:end]
10print(text[0:3])   # Pyt (from position 0 up to 3, not including 3)
11print(text[2:5])   # tho
12print(text[:3])    # Pyt (from the start up to 3)
13print(text[3:])    # hon (from 3 to the end)
📌 Remember: In programming, we count from 0, not from 1. The first character of a text is at position 0, the second at position 1, and so on.

f-strings: the modern way to combine text and variables

The most convenient way to mix text with variables in Python is using f-strings. Just put an f before the quotes and place your variables inside curly braces {}:

python
1name = "Maria"
2age = 25
3
4# With f-string (recommended way)
5message = f"Hello, my name is {name} and I am {age} years old"
6print(message)  # Hello, my name is Maria and I am 25 years old
7
8# You can put expressions inside the braces
9price = 49.99
10print(f"The price with tax is: {price * 1.08:.2f}")  # The price with tax is: 53.99

User input: the input() function

So far, we have written all values directly in the code. But in a real program, you often need to ask the user for information. That is what the input() function is for:

python
1# Ask the user for their name
2name = input("What is your name? ")
3print(f"Hello, {name}! Welcome to the course.")

When Python reaches the input() line, the program pauses and waits for the user to type something and press Enter. Whatever the user types gets stored in the variable.

⚠️ Very important: The input() function always returns text (type str), even if the user types a number. If you need a number, you must convert it with int() or float():
python
1# This does NOT work as expected
2age = input("How old are you? ")
3print(type(age))  # <class 'str'> — it is text, not a number
4
5# This DOES work
6age = int(input("How old are you? "))
7print(type(age))  # <class 'int'> — now it is a number
8print(f"In 5 years you will be {age + 5} years old")

Practical example: simple calculator

Let's put everything we learned into practice by creating a simple calculator that asks the user for two numbers and shows the results of all operations. Create a file called calculator.py:

python
1# calculator.py - My first Python calculator
2
3print("=" * 40)
4print("   PYTHON CALCULATOR")
5print("=" * 40)
6
7# Ask the user for numbers
8number1 = float(input("Enter the first number: "))
9number2 = float(input("Enter the second number: "))
10
11# Perform the operations
12addition = number1 + number2
13subtraction = number1 - number2
14multiplication = number1 * number2
15
16print()
17print(f"Results for {number1} and {number2}:")
18print("-" * 40)
19print(f"  Addition:       {number1} + {number2} = {addition}")
20print(f"  Subtraction:    {number1} - {number2} = {subtraction}")
21print(f"  Multiplication: {number1} * {number2} = {multiplication}")
22
23# Division needs special care (cannot divide by 0)
24if number2 != 0:
25    division = number1 / number2
26    floor_div = number1 // number2
27    remainder = number1 % number2
28    print(f"  Division:       {number1} / {number2} = {division}")
29    print(f"  Floor division: {number1} // {number2} = {floor_div}")
30    print(f"  Remainder:      {number1} % {number2} = {remainder}")
31else:
32    print("  Division: Cannot divide by 0")
33
34power = number1 ** number2
35print(f"  Power:          {number1} ** {number2} = {power}")
36print("-" * 40)
37print("Thanks for using the calculator!")

Run the program with python calculator.py and try it with different numbers. Here is an example of what it looks like:

bash
1========================================
2   PYTHON CALCULATOR
3========================================
4Enter the first number: 10
5Enter the second number: 3
6
7Results for 10.0 and 3.0:
8----------------------------------------
9  Addition:       10.0 + 3.0 = 13.0
10  Subtraction:    10.0 - 3.0 = 7.0
11  Multiplication: 10.0 * 3.0 = 30.0
12  Division:       10.0 / 3.0 = 3.3333333333333335
13  Floor division: 10.0 // 3.0 = 3.0
14  Remainder:      10.0 % 3.0 = 1.0
15  Power:          10.0 ** 3.0 = 1000.0
16----------------------------------------
17Thanks for using the calculator!
💡 Tip: Do not worry if you see the if line and do not understand it yet. Conditionals (if/else) will be covered in detail in an upcoming article. For now, just know that this line asks "is the second number different from zero?" to avoid a division error.

Summary and next article

In this second article of the course, we learned fundamental concepts:

  • Variables are like labeled boxes where you store data
  • The four basic types: int (integers), float (decimals), str (text), bool (true/false)
  • The type() function to check a variable's type
  • Casting to convert between types: int(), float(), str()
  • Number operations: addition, subtraction, multiplication, division, exponentiation, modulo
  • String operations: concatenation, repetition, length, slicing, f-strings
  • The input() function to get data from the user
  • We built a calculator that combines everything we learned

In the next article (Part 3 of 10), we will learn about control structures: conditionals — how to make your program make decisions using if, elif, and else. This is what makes programs truly smart.

See you in the next article!

Share:
CV

Cristhian Villegas

Software Engineer specializing in Java, Spring Boot, Angular & AWS. Building scalable distributed systems with clean architecture.

Comments

Sign in to leave a comment

No comments yet. Be the first!

Related Articles