Back to blog
← View series: python tutorials

~/blog

Variables and Basic Data Types

Apr 1, 20264 min readBy Mohammed Vasim
PythonProgrammingTutorialBeginner

Introduction

In this tutorial, you'll learn how Python stores and manipulates data using variables and understand the different data types available in Python.

Variables are the foundation of any program - they're how we store information that our code can use and manipulate.

What You'll Learn

  • How to create and use variables
  • The basic data types in Python
  • Type conversion (converting between data types)
  • Best practices for naming variables

What are Variables?

Variables are containers for storing data values. Think of them as labeled boxes where you can put information.

Creating Variables

In Python, creating a variable is simple - just assign a value using the equals sign (=):

python
# Creating variables
name = "Alice"        # A string (text)
age = 25              # An integer (whole number)
height = 5.9          # A float (decimal number)
is_student = True     # A boolean (True/False)

# Printing variables
print(name)           # Output: Alice
print(age)            # Output: 25
print(height)         # Output: 5.9
print(is_student)     # Output: True

How Variables Work

Python automatically determines the data type based on the value you assign:

python
x = 10        # Python knows this is an integer
y = "Hello"   # Python knows this is a string
z = 3.14      # Python knows this is a float

Basic Data Types

Python has several built-in data types. Let's explore the most common ones:

1. Integers (int)

Integers are whole numbers without decimals:

python
# Integer examples
count = 42
temperature = -10
population = 8000000

print(type(count))        # Output: <class 'int'>
print(type(temperature))  # Output: <class 'int'>

2. Floats (float)

Floats are numbers with decimal points:

python
# Float examples
price = 19.99
pi = 3.14159
temperature = 98.6

print(type(price))        # Output: <class 'float'>
print(type(pi))           # Output: <class 'float'>

3. Strings (str)

Strings are text enclosed in quotes:

python
# String examples
name = "Python"
message = 'Hello, World!'
multiline = """This is a
multi-line string"""

print(type(name))         # Output: <class 'str'>
print(type(message))      # Output: <class 'str'>

You can use either single quotes (') or double quotes (") - they're interchangeable!

4. Booleans (bool)

Booleans represent truth values - either True or False:

python
# Boolean examples
is_active = True
has_permission = False
is_adult = 25 > 18        # This evaluates to True

print(type(is_active))    # Output: <class 'bool'>
print(is_adult)           # Output: True

Important: Boolean values must start with capital letters (True, False)

Working with Strings

Strings are one of the most used data types. Let's explore them further:

String Operations

python
# Concatenation (joining strings)
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)          # Output: John Doe

# Repetition
echo = "Ha" * 3
print(echo)               # Output: HaHaHa

# Length
message = "Hello"
print(len(message))       # Output: 5

# Indexing (accessing individual characters)
word = "Python"
print(word[0])            # Output: P (first character)
print(word[-1])           # Output: n (last character)

String Methods

Python provides many built-in methods for strings:

python
text = "  Hello, Python!  "

# Removing whitespace
print(text.strip())       # Output: Hello, Python!

# Changing case
print(text.upper())       # Output:   HELLO, PYTHON!
print(text.lower())       # Output:   hello, python!
print(text.title())       # Output:   Hello, Python!

# Finding and replacing
print(text.replace("Python", "World"))  # Output:   Hello, World!

Type Conversion

Sometimes you need to convert between data types. Python makes this easy:

Converting to String

python
age = 25
price = 19.99

age_str = str(age)        # "25"
price_str = str(price)    # "19.99"

Converting to Number

python
# String to Integer
num_str = "42"
num = int(num_str)        # 42

# String to Float
pi_str = "3.14"
pi = float(pi_str)        # 3.14

# Integer to Float
whole = 10
decimal = float(whole)    # 10.0

Getting User Input

You can get input from users using the input() function:

python
# Getting string input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Getting numeric input (must convert!)
age = int(input("Enter your age: "))
next_year = age + 1
print(f"You'll be {next_year} next year.")

Variable Naming Rules

Python has specific rules for naming variables:

✅ Valid Variable Names

python
name = "John"             # lowercase
user_name = "john"        # snake_case (recommended)
age = 25                  # short and descriptive
is_active = True          # booleans often start with is/has/can

❌ Invalid Variable Names

python
2name = "John"            # Cannot start with a number
my-name = "John"          # Cannot use hyphens
my name = "John"          # Cannot use spaces

Naming Conventions

ConventionUse For
snake_caseVariables, functions (recommended in Python)
CamelCaseClasses
UPPERCASEConstants

Summary

In this tutorial, you learned:

  • ✅ How to create and use variables
  • ✅ Four basic data types: int, float, str, bool
  • ✅ How to work with strings (concatenation, methods)
  • ✅ How to convert between data types
  • ✅ How to get user input
  • ✅ Variable naming rules and conventions

🧑‍💻 Practice Exercise

Create a program that:

  1. Asks the user for their name
  2. Asks for their age
  3. Asks for their favorite number
  4. Prints a summary showing all the information
Click to see solution
python
# User information program
name = input("What is your name? ")
age = int(input("How old are you? "))
favorite_number = float(input("What is your favorite number? "))

print("\n--- Your Information ---")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Number: {favorite_number}")
print(f"Next year you'll be {age + 1} years old!")

What's Next

In the next tutorial, we'll learn about Basic Operators - how to perform calculations and comparisons in Python.

Basic Operators →

Comments (0)

No comments yet. Be the first to comment!

Leave a comment