Python Data Types and Operators

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will explore fundamental Python data types and operators. Building upon your knowledge from the previous lab, you will learn about integers, floating-point numbers, strings, and boolean values. You will also practice using various operators to perform calculations and comparisons. This hands-on experience will deepen your understanding of Python's core concepts and prepare you for more advanced programming tasks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") subgraph Lab Skills python/variables_data_types -.-> lab-393077{{"`Python Data Types and Operators`"}} python/numeric_types -.-> lab-393077{{"`Python Data Types and Operators`"}} python/strings -.-> lab-393077{{"`Python Data Types and Operators`"}} python/booleans -.-> lab-393077{{"`Python Data Types and Operators`"}} python/type_conversion -.-> lab-393077{{"`Python Data Types and Operators`"}} end

Understanding Numeric Data Types

In this step, you will work with two primary numeric data types in Python: integers and floating-point numbers.

  1. Open the Python interpreter by typing the following command in your terminal:

    python

    You should see the Python prompt (>>>), indicating that you're now in the Python interactive shell.

    Python Interpreter
  2. Let's start by exploring integers. In the Python interpreter, type the following:

    >>> age = 25
    >>> print(f"I am {age} years old.")
    I am 25 years old.
    >>> type(age)
    <class 'int'>

    Here, age is an integer variable. The type() function confirms that it's an int (integer) data type. Integers are whole numbers without decimal points.

  3. Now, let's work with floating-point numbers:

    >>> height = 1.75
    >>> print(f"My height is {height} meters.")
    My height is 1.75 meters.
    >>> type(height)
    <class 'float'>

    height is a floating-point number, represented by the float data type in Python. Floats are used for numbers with decimal points.

  4. Let's perform a calculation using these numeric types:

    >>> weight = 70  ## Let's define weight first
    >>> bmi = weight / (height ** 2)
    >>> print(f"My BMI is {bmi:.2f}")
    My BMI is 22.86

    Here, we first define weight. The ** operator is used for exponentiation (raising to a power). The .2f in the f-string formats the output to show only two decimal places.

    # is used for comments in Python. Comments are ignored by the interpreter and are used to document code.

If you make a mistake or want to try different values, don't worry! You can simply redefine the variables and run the calculations again.

Working with Strings

In this step, you will learn how to work with strings, which are sequences of characters in Python.

  1. In the Python interpreter, create a string variable:

    >>> name = "Alice"
    >>> print(f"Hello, {name}!")
    Hello, Alice!
    >>> type(name)
    <class 'str'>

    The str data type represents strings in Python. Strings are enclosed in either single quotes ('') or double quotes ("").

  2. Strings support various operations. Let's explore some:

    >>> ## String concatenation (joining strings)
    >>> first_name = "John"
    >>> last_name = "Doe"
    >>> full_name = first_name + " " + last_name
    >>> print(full_name)
    John Doe
    
    >>> ## String repetition
    >>> echo = "Hello " * 3
    >>> print(echo)
    Hello Hello Hello
    
    >>> ## String length
    >>> print(len(full_name))
    8
    
    >>> ## Accessing characters in a string
    >>> print(full_name[0])  ## First character (index 0)
    J
    >>> print(full_name[-1])  ## Last character
    e

    Remember, in Python, indexing starts at 0, so the first character is at index 0.

  3. Strings in Python are immutable, meaning you can't change individual characters. However, you can create new strings based on existing ones:

    >>> uppercase_name = full_name.upper()
    >>> print(uppercase_name)
    JOHN DOE
    
    >>> lowercase_name = full_name.lower()
    >>> print(lowercase_name)
    john doe

    These methods don't change the original string, but create new ones.

Understanding Boolean Values and Comparison Operators

In this step, you will learn about boolean values and how to use comparison operators in Python.

  1. Boolean values in Python are either True or False. Let's create some boolean variables:

    >>> is_student = True
    >>> is_employed = False
    >>> print(f"Is a student: {is_student}")
    Is a student: True
    >>> print(f"Is employed: {is_employed}")
    Is employed: False
    >>> type(is_student)
    <class 'bool'>

    Boolean values are often used in conditional statements and loops, which you'll learn about in future labs.

  2. Comparison operators return boolean values. Let's explore some comparisons:

    >>> x = 5
    >>> y = 10
    >>> print(x < y)   ## Less than
    True
    >>> print(x > y)   ## Greater than
    False
    >>> print(x == y)  ## Equal to
    False
    >>> print(x != y)  ## Not equal to
    True
    >>> print(x <= y)  ## Less than or equal to
    True
    >>> print(x >= y)  ## Greater than or equal to
    False

    These operators compare values and return True or False based on the comparison.

  3. You can also use comparison operators with other data types:

    >>> name1 = "Alice"
    >>> name2 = "Bob"
    >>> print(name1 < name2)  ## Alphabetical comparison
    True
    
    >>> print(len(name1) == len(name2))  ## Comparing string lengths
    True

    When comparing strings, Python uses lexicographic ordering (dictionary order).

  4. Boolean operators (and, or, not) can be used to combine boolean values:

    >>> a = True
    >>> b = False
    >>> print(a and b)  ## True if both are True
    False
    >>> print(a or b)   ## True if at least one is True
    True
    >>> print(not a)    ## Negation
    False

    These operators are useful for creating complex conditions in your programs.

Exploring Type Conversion

In this step, you will learn how to convert between different data types in Python.

  1. Sometimes you need to convert one data type to another. Python provides built-in functions for this purpose. Let's start with converting strings to numbers:

    >>> ## Converting string to integer
    >>> age_str = "25"
    >>> age_int = int(age_str)
    >>> print(f"Age: {age_int}")
    Age: 25
    >>> print(type(age_int))
    <class 'int'>
    
    >>> ## Converting string to float
    >>> height_str = "1.75"
    >>> height_float = float(height_str)
    >>> print(f"Height: {height_float} meters")
    Height: 1.75 meters
    >>> print(type(height_float))
    <class 'float'>

    The int() and float() functions convert strings to integers and floats, respectively. Be careful: if the string can't be converted, you'll get an error.

  2. You can also convert numbers to strings:

    >>> ## Converting integer to string
    >>> count = 42
    >>> count_str = str(count)
    >>> print(f"The count is: {count_str}")
    The count is: 42
    >>> print(type(count_str))
    <class 'str'>
    
    >>> ## Converting float to string
    >>> pi = 3.14159
    >>> pi_str = str(pi)
    >>> print(f"Pi is approximately {pi_str}")
    Pi is approximately 3.14159
    >>> print(type(pi_str))
    <class 'str'>

    The str() function can convert most Python objects to strings.

  3. Boolean values can be converted to and from other types:

    >>> ## Converting to boolean
    >>> print(bool(1))     ## Non-zero numbers are True
    True
    >>> print(bool(0))     ## Zero is False
    False
    >>> print(bool(""))    ## Empty string is False
    False
    >>> print(bool("Hello"))  ## Non-empty string is True
    True
    
    >>> ## Converting boolean to integer
    >>> true_int = int(True)
    >>> false_int = int(False)
    >>> print(f"True as integer: {true_int}")
    True as integer: 1
    >>> print(f"False as integer: {false_int}")
    False as integer: 0

    In Python, any non-zero number or non-empty string is considered True when converted to a boolean.

Putting It All Together

In this final step, you will create a simple program that utilizes the concepts you've learned in this lab.

  1. Exit the Python interpreter by typing exit() or pressing Ctrl+D.

  2. Switch to the WebIDE tab in LabEx VM. WebIDE is an online code editor that allows you to write and run Python scripts directly in your browser. It's suitable for longer scripts and projects.

    WebIDE
  3. Create a new file named data_types_practice.py in the ~/project directory using the following command:

    touch ~/project/data_types_practice.py
  4. Click on the newly created file to open it in the editor.

  5. Copy and paste the following code into the file:

    ## Data types and operators practice
    
    ## Get user input
    name = input("Enter your name: ")
    age_str = input("Enter your age: ")
    height_str = input("Enter your height in meters: ")
    
    ## Convert input to appropriate types
    age = int(age_str)
    height = float(height_str)
    
    ## Perform calculations
    birth_year = 2024 - age
    is_adult = age >= 18
    
    ## Create output string
    output = f"""
    Name: {name}
    Age: {age}
    Height: {height:.2f} meters
    Birth Year: {birth_year}
    Is Adult: {is_adult}
    """
    
    ## Print the result
    print(output)
    
    ## Bonus: String manipulation
    uppercase_name = name.upper()
    name_length = len(name)
    
    print(f"Your name in uppercase: {uppercase_name}")
    print(f"Your name has {name_length} characters")

    This program demonstrates the use of various data types, type conversion, string formatting, and basic calculations.

  6. Save the file (Auto save is enabled) and run it using the following command:

    python ~/project/data_types_practice.py
  7. Enter your information when prompted. You should see output similar to this:

    Enter your name: Alice
    Enter your age: 25
    Enter your height in meters: 1.75
    
    Name: Alice
    Age: 25
    Height: 1.75 meters
    Birth Year: 1999
    Is Adult: True
    
    Your name in uppercase: ALICE
    Your name has 5 characters
    alt text

If you make a mistake while entering data, you'll need to run the program again. This is a good opportunity to practice running Python scripts multiple times with different inputs.

Summary

In this lab, you have explored fundamental Python data types and operators. You have learned how to work with integers, floating-point numbers, strings, and boolean values. You have practiced using various operators to perform calculations and comparisons, and you have gained experience with type conversion. Finally, you applied these concepts to create a simple program that takes user input, processes it, and produces formatted output.

These skills form the foundation of Python programming and will be essential as you continue to develop more complex programs. Remember to practice these concepts regularly to reinforce your understanding and become more comfortable with Python syntax and data manipulation.

As you progress, don't hesitate to experiment with the Python interpreter. It's a great tool for testing small code snippets and understanding how different operations work. If you encounter any errors, read the error messages carefully - they often provide clues about what went wrong and how to fix it.

Other Python Tutorials you may like