Python Data Types and Operators

PythonBeginner
Practice Now

Introduction

Welcome to the world of Python! In this lab, you'll get to know the basic building blocks of Python programming: data types and operators. We'll explore numbers, text, and true/false values. You'll also learn how to perform calculations and comparisons. This lab is designed for beginners, so we'll go step-by-step. Don't worry if it's all new—we're here to guide you. Let's get started!

Understanding Numbers in Python

In this step, we'll look at two main types of numbers in Python: integers (whole numbers) and floats (numbers with decimals).

First, open the Python interpreter. This is a tool that lets you run Python code one line at a time. For beginners, the Desktop Interface is more user-friendly. If you're comfortable with the terminal, you can switch to the separate Terminal Tab from the top-left corner for smoother operation. Both approaches achieve the same result.

Terminal Tab

Type this in your terminal:

python

You should see >>>. This means Python is ready for your commands.

Python Interpreter

Let's start with integers. Integers are whole numbers, like -1, 0, and 100.

books = 5
print(f"I have {books} books.")
type(books)

Output:

I have 5 books.
<class 'int'>

Here, we created a variable named books and gave it the value 5. A variable is like a box where you can store information. The print() function displays output to the screen. We used an f-string (notice the f before the quotes) to easily include the value of our books variable inside the text. The type() function tells us that books holds an int (integer).

Next, let's explore floating-point numbers, or floats. These are numbers with a decimal point.

price = 19.99
print(f"This book costs ${price}.")
type(price)

Output:

This book costs $19.99.
<class 'float'>

The variable price is a float because it has a decimal point.

Now, let's do a simple calculation. Python can be used as a calculator!

quantity = 3
total_cost = price * quantity  ## Let's calculate the total cost
print(f"The total cost for {quantity} books is ${total_cost:.2f}.")

Output:

The total cost for 3 books is $59.97.

We used the * operator to multiply price and quantity. The .2f in the f-string formats the number to two decimal places. The # symbol starts a comment. Comments are notes for humans that Python ignores.

Feel free to try your own calculations! You can redefine variables with new values and see what happens.

Working with Text (Strings)

In this step, you'll learn about strings, which are used to represent text in Python.

Let's create a string variable in the Python interpreter. Strings are always surrounded by single (') or double (") quotes.

name = "Alice"
print(f"Hello, {name}!")
type(name)

Output:

Hello, Alice!
<class 'str'>

The str data type represents a string in Python.

Strings can be combined or manipulated in many ways. Let's try some common operations.

## Joining two strings together (concatenation)
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

Output:

John Doe
## Repeating a string
cheer = "Go! " * 3
print(cheer)

Output:

Go! Go! Go!
## Finding the length of a string
print(len(full_name))

Output:

8
## Accessing individual characters
print(full_name[0])  ## Get the first character
print(full_name[-1]) ## Get the last character

Output:

J
e

Important: Python starts counting from 0. So, the first character is at index 0. The index -1 is a handy shortcut for the last character.

Strings in Python are immutable, which means they cannot be changed after they are created. You can't change a single character in a string. However, you can create new strings from an existing one.

message = "Hello World"
uppercase_message = message.upper()
print(uppercase_message)

Output:

HELLO WORLD
lowercase_message = message.lower()
print(lowercase_message)

Output:

hello world

The .upper() and .lower() methods create new strings. The original message variable remains unchanged.

True or False? (Booleans)

In this step, you'll learn about boolean values, which can only be True or False. They are essential for making decisions in your code.

Let's create some boolean variables. Note that True and False start with a capital letter in Python.

is_learning = True
is_finished = False
print(f"Are we learning Python? {is_learning}")
type(is_learning)

Output:

Are we learning Python? True
<class 'bool'>

The bool data type represents boolean values.

Comparison operators are used to compare two values, and they always result in a boolean (True or False).

x = 5
y = 10
print(x < y)   ## Is x less than y?
print(x == y)  ## Is x equal to y?
print(x != y)  ## Is x not equal to y?

Output:

True
False
True

Here are the common comparison operators: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to).

You can also compare strings. Python compares them alphabetically.

name1 = "Alice"
name2 = "Bob"
print(name1 < name2)  ## "Alice" comes before "Bob" alphabetically

Output:

True

Boolean operators (and, or, not) are used to combine boolean expressions.

a = True
b = False
print(a and b)  ## True only if both a AND b are True
print(a or b)   ## True if either a OR b (or both) are True
print(not a)    ## The opposite of a

Output:

False
True
False

These operators help you create more complex conditions for your programs.

Converting Between Data Types

Sometimes, you need to convert a value from one data type to another. This is called type conversion or "casting."

Let's convert a string to a number. This is very common when you get input from a user, as input is always read as a string.

age_string = "25"
age_number = int(age_string) ## Convert string to integer
print(age_number + 5)

Output:

30
price_string = "1.99"
price_float = float(price_string) ## Convert string to float
print(price_float * 2)

Output:

3.98

We use int() to convert to an integer and float() to convert to a float. Be careful! If you try to convert a string that doesn't look like a number (e.g., int("hello")), Python will show an error.

You can also convert numbers to strings using the str() function.

count = 50
count_string = str(count)
print("The count is " + count_string)

Output:

The count is 50

Finally, you can convert values to booleans using bool(). The rules are simple:

  • 0, empty strings (""), and some special empty objects are False.
  • Almost everything else is True (any non-zero number, any non-empty string).
print(bool(100))      ## Non-zero number
print(bool(0))        ## Zero
print(bool("Hello"))  ## Non-empty string
print(bool(""))       ## Empty string

Output:

True
False
True
False

Type conversion is a powerful tool for making different data types work together.

Putting It All Together

In this final step, let's write a small program that uses everything we've learned.

Switch to the WebIDE tab in the LabEx VM. The WebIDE is an online code editor where you can write and save your Python scripts.

WebIDE online code editor

For more detailed information about the WebIDE interface, please refer to the LabEx VM WebIDE documentation.

Create a new file named user_info.py in the ~/project directory with this command:

touch ~/project/user_info.py

Click on the new file in the file explorer on the left to open it in the editor.

Copy and paste the following code into the file:

## A simple program to practice data types

## Get user input (input is always a string)
name = input("Enter your name: ")
age_str = input("Enter your age: ")

## Convert age to an integer
age = int(age_str)

## Perform a simple calculation
years_to_100 = 100 - age
is_adult = age >= 18

## Create an output message using an f-string
output = f"""
--- User Information ---
Hello, {name}!
You are {age} years old.
You will be 100 years old in {years_to_100} years.
Are you an adult? {is_adult}
--- End of Report ---
"""

## Print the final result
print(output)

This script uses the input() function to ask for a name and age. input() always gives us the user's entry as a string, which is why we need to convert the age to a number using int(). The script then creates a multi-line f-string for the output, using triple quotes ("""). This is a neat way to format text that spans several lines. Finally, it performs some calculations and prints the formatted summary.

Save the file (it should auto-save) and run it from the terminal with this command:

python ~/project/user_info.py

The program will ask for your name and age. After you provide them, it will print the summary.

Enter your name: Alice
Enter your age: 25

--- User Information ---
Hello, Alice!
You are 25 years old.
You will be 100 years old in 75 years.
Are you an adult? True
--- End of Report ---
Program output example

Feel free to run the script multiple times with different inputs to see how the output changes!

Summary

Congratulations on completing this lab! You've taken a huge first step into the world of Python programming.

In this lab, you learned about the fundamental building blocks of Python:

  • Numeric Types: You worked with integers (int) for whole numbers and floats (float) for decimal numbers.
  • Strings (str): You learned how to create and manipulate text.
  • Booleans (bool): You explored True and False values and used them for comparisons.
  • Operators: You used arithmetic (*), comparison (==, <), and boolean (and, or) operators.
  • Type Conversion: You practiced converting between different data types, like turning a string into a number.

These concepts are the foundation for everything you will do in Python. Keep practicing, and don't be afraid to experiment in the Python interpreter—it's one of the best ways to learn. Well done, and happy coding!