Python Variables and Data Types

PythonBeginner
Practice Now

Introduction

In this lab, you will learn the fundamental concepts of Python variables and data types. Variables are essential building blocks in programming that allow you to store, access, and manipulate data in your code. Understanding different data types is crucial for writing effective Python programs.

You will create various variables, explore different data types available in Python, perform type conversions, and learn how to use variables in expressions. These skills form the foundation of Python programming and are necessary for developing more complex applications.

By the end of this lab, you will be comfortable creating and using variables with different data types in Python.

Creating Your First Python Variables

In this step, you will learn how to create and use variables in Python. Variables are containers that store data values and give them meaningful names for easier reference in your code.

Let's start by creating a new Python file and defining some basic variables:

  1. Open the file /home/labex/project/variables.py in the WebIDE.

  2. Add the following code to define three variables:

## Creating basic variables
water_supply = 100    ## Amount of water in gallons
food_supply = 50      ## Amount of food in pounds
ammunition = 40       ## Number of ammunition rounds

In Python, you create a variable by specifying a name followed by the equals sign (=) and then the value you want to assign to it.

  1. Let's add code to display the values of these variables:
## Displaying variable values
print("Water supply:", water_supply)
print("Food supply:", food_supply)
print("Ammunition:", ammunition)
  1. Run your script by opening a terminal in the WebIDE and executing:
python3 /home/labex/project/variables.py

You should see the following output:

Water supply: 100
Food supply: 50
Ammunition: 40

Congratulations. You have created your first Python variables and displayed their values. These variables store information that your program can access and manipulate.

Understanding Numeric Data Types

Python has several data types that are used to classify different types of data. In this step, you will learn about two numeric data types: integers and floats.

  1. Open the file /home/labex/project/variables.py in the WebIDE.

  2. Add the following code to the file to define variables with different numeric data types:

## Numeric data types
integer_value = 42        ## Integer (whole number)
float_value = 3.14159     ## Float (decimal number)
  1. Let's explore the types of these variables using the type() function:
## Check the data types
print("\nUnderstanding data types:")
print("integer_value:", integer_value, "- Type:", type(integer_value))
print("float_value:", float_value, "- Type:", type(float_value))
  1. Now let's perform some basic operations with these numeric types:
## Basic operations with numbers
sum_result = integer_value + float_value
product_result = integer_value * float_value

print("\nBasic operations:")
print(f"{integer_value} + {float_value} = {sum_result}")
print(f"{integer_value} * {float_value} = {product_result}")
  1. Run your script:
python3 /home/labex/project/variables.py

You should see output similar to:

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

Notice that when you perform operations with integers and floats, Python automatically converts the result to a float if needed.

Working with Strings and Booleans

In addition to numeric data types, Python provides strings for text data and booleans for true/false values. Let's explore these types:

  1. Open the file /home/labex/project/variables.py in the WebIDE.

  2. Add the following code to define string and boolean variables:

## String data type - for text
camp_name = "Python Base Camp"
location = 'Programming Valley'  ## Strings can use single or double quotes

## Boolean data type - for true/false values
is_safe = True
has_water = True
enemy_nearby = False
  1. Add code to check and display these variables:
## Displaying string and boolean variables
print("\nString variables:")
print("Camp name:", camp_name, "- Type:", type(camp_name))
print("Location:", location, "- Type:", type(location))

print("\nBoolean variables:")
print("Is the camp safe?", is_safe, "- Type:", type(is_safe))
print("Is water available?", has_water, "- Type:", type(has_water))
print("Is enemy nearby?", enemy_nearby, "- Type:", type(enemy_nearby))
  1. Let's also demonstrate some string operations:
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)

## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
  1. Run your script:
python3 /home/labex/project/variables.py

You should see output similar to:

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

String variables:
Camp name: Python Base Camp - Type: <class 'str'>
Location: Programming Valley - Type: <class 'str'>

Boolean variables:
Is the camp safe? True - Type: <class 'bool'>
Is water available? True - Type: <class 'bool'>
Is enemy nearby? False - Type: <class 'bool'>

Full location: Python Base Camp in Programming Valley
--------------------
Camp Information
--------------------

Notice how strings can be concatenated with the + operator and repeated with the * operator. Booleans are useful for representing conditions and controlling program flow.

Type Conversion and Type Checking

Sometimes you need to convert values from one data type to another or check the data type of a variable. This is called type conversion (or type casting). Let's explore this concept:

  1. Open the file /home/labex/project/variables.py in the WebIDE.

  2. Add code to demonstrate type conversion:

## Type conversion examples
print("\nType Conversion Examples:")

## Converting string to integer
supplies_str = "75"
supplies_int = int(supplies_str)
print(f"String '{supplies_str}' converted to integer: {supplies_int} - Type: {type(supplies_int)}")

## Converting integer to string
days_int = 30
days_str = str(days_int)
print(f"Integer {days_int} converted to string: '{days_str}' - Type: {type(days_str)}")

## Converting integer to float
distance_int = 100
distance_float = float(distance_int)
print(f"Integer {distance_int} converted to float: {distance_float} - Type: {type(distance_float)}")

## Converting float to integer (note: this truncates the decimal part)
temperature_float = 32.7
temperature_int = int(temperature_float)
print(f"Float {temperature_float} converted to integer: {temperature_int} - Type: {type(temperature_int)}")
  1. Add code to check data types:
## Type checking
print("\nType Checking Examples:")
value1 = 42
value2 = "42"
value3 = 42.0

print(f"Is {value1} an integer? {isinstance(value1, int)}")
print(f"Is {value2} an integer? {isinstance(value2, int)}")
print(f"Is {value3} a float? {isinstance(value3, float)}")
print(f"Is {value2} a string? {isinstance(value2, str)}")
  1. Run your script:
python3 /home/labex/project/variables.py

You should see output similar to:

...previous output...

Type Conversion Examples:
String '75' converted to integer: 75 - Type: <class 'int'>
Integer 30 converted to string: '30' - Type: <class 'str'>
Integer 100 converted to float: 100.0 - Type: <class 'float'>
Float 32.7 converted to integer: 32 - Type: <class 'int'>

Type Checking Examples:
Is 42 an integer? True
Is 42 an integer? False
Is 42.0 a float? True
Is 42 a string? True

Notice that:

  • int() converts values to integers
  • float() converts values to floating-point numbers
  • str() converts values to strings
  • When converting a float to an integer, the decimal part is truncated (not rounded)
  • isinstance() function checks if a variable is of a specific type

These conversion functions are useful when you need to process input from users or when working with data from different sources.

Variables in Expressions and Decision Making

Variables become truly powerful when used in expressions and decision-making structures. Let's explore how to use variables in calculations and conditional statements:

  1. Open the file /home/labex/project/variables.py in the WebIDE.

  2. Add code to demonstrate using variables in calculations:

## Variables in expressions
print("\nVariables in Expressions:")

water_per_day = 4  ## gallons
food_per_day = 2.5  ## pounds

## Calculate how long supplies will last
water_days = water_supply / water_per_day
food_days = food_supply / food_per_day

print(f"With {water_supply} gallons of water, consuming {water_per_day} gallons per day, water will last {water_days} days")
print(f"With {food_supply} pounds of food, consuming {food_per_day} pounds per day, food will last {food_days} days")
  1. Add code to demonstrate using variables in conditional statements:
## Using variables for decision making
print("\nDecision Making with Variables:")

## Check which supply will run out first
if water_days < food_days:
    limiting_factor = "Water"
    limiting_days = water_days
else:
    limiting_factor = "Food"
    limiting_days = food_days

print(f"{limiting_factor} will run out first, after {limiting_days} days")

## Check if supplies are sufficient for a 10-day journey
journey_days = 10
sufficient_supplies = water_days >= journey_days and food_days >= journey_days and ammunition >= 20

print(f"Planning a {journey_days}-day journey.")
print(f"Do we have sufficient supplies? {sufficient_supplies}")

## Provide specific supply status
if water_days < journey_days:
    print(f"Warning: Water will only last {water_days:.1f} days.")
if food_days < journey_days:
    print(f"Warning: Food will only last {food_days:.1f} days.")
if ammunition < 20:
    print(f"Warning: Only {ammunition} rounds of ammunition available.")
  1. Run your script:
python3 /home/labex/project/variables.py

You should see output similar to:

...previous output...

Variables in Expressions:
With 100 gallons of water, consuming 4 gallons per day, water will last 25.0 days
With 50 pounds of food, consuming 2.5 pounds per day, food will last 20.0 days

Decision Making with Variables:
Food will run out first, after 20.0 days
Planning a 10-day journey.
Do we have sufficient supplies? True

This demonstrates how you can use variables in mathematical calculations and how to make decisions based on variable values. Notice how we use comparison operators (<, >=) and logical operators (and) to create conditions.

The formatting syntax {water_days:.1f} specifies that the float should be displayed with one decimal place.

Summary

In this lab, you have learned the fundamental concepts of Python variables and data types. You have created and used variables of different types, including:

  • Integers for whole numbers
  • Floats for decimal numbers
  • Strings for text data
  • Booleans for true/false values

You have also learned how to:

  • Check the type of a variable using the type() function
  • Convert between different data types using functions like int(), float(), and str()
  • Use variables in expressions and calculations
  • Make decisions based on variable values using conditional statements

These concepts form the foundation of Python programming. Variables allow you to store and manipulate data, while understanding different data types helps you use the right type for each situation. As you continue your Python journey, you will build upon these basics to create more complex and powerful programs.