Welcome to your third lesson! In our previous session, you learned the two fundamental ways to run Python code: interactively in the shell for quick tests, and by executing a script file for building lasting programs. You now have a working development environment and the ability to execute code.
This lesson addresses the natural next question: what do we write in that code? Programs work by processing information, so our first step is to learn how to represent that information. You'll learn to use variables to store data, and you'll be introduced to Python's four most basic data types: numbers for quantities, strings for text, and booleans for true/false states. We will also cover how to convert data from one type to another, a crucial skill for handling user input. These concepts are the absolute foundation for building any application, including the support chatbot you'll be creating.
Variables: Naming Your Data
At its core, a program manipulates data. To do this effectively, we need a way to label and store values in the computer's memory so we can refer to them later. We do this using variables. Think of a variable as a labeled box where you can put a piece of information. You give the box a name (the variable name) and put something inside it (the value).
The syntax for this in Python is simple: name = value. The equals sign (=) is the assignment operator; it assigns the value on the right to the variable on the left.
To get a clear introduction to this core concept, start by reading the first section of the CS50 lecture notes on variables.
Lecture 0 - CS50's Introduction to Programming with Python
These notes provide a concise, practical explanation of what variables are and how they are used to store values, particularly the value returned from the input() function.
Please read the section titled Variables. Focus on understanding the role of the = sign as an assignment operator, which stores the result of the expression on the right into the variable on the left.
The following video from Bro Code offers a great complementary explanation, demonstrating how variables are declared and used in code.
Python variables for beginners ❎
This video clearly explains the concept of a variable as a reusable container for a value and shows you how to declare one in Python.
Watch the segment from the beginning until the end of the initial explanation of variables and how to print them.
Basic Data Types
The values you store in variables have a "type." Python needs to know whether a value is text, a whole number, a number with a decimal, or a simple true/false flag. Understanding these types is critical because the type determines what you can do with the value. For example, you can perform mathematical addition on two numbers, but it doesn't make sense to do that with two pieces of text.
Python has several built-in data types, but we'll start with the four most essential ones:
- Strings (
str): For representing text. Example:"Hello, world!"or'INC00101'. - Integers (
int): For representing whole numbers. Example:42,-10,0. - Floats (
float): For representing numbers with a decimal point. Example:3.14,19.95. - Booleans (
bool): For representing truth values. It can only beTrueorFalse.
The following comprehensive article from Real Python is an excellent reference for these types. We will be referring to it throughout this section.
Basic Data Types in Python: A Quick Exploration – Real Python
This article provides a detailed breakdown of Python's fundamental data types. It covers how to create them (literals), what they represent, and how to convert between them.
For now, you don't need to read the entire article. I will guide you to the specific sections as we introduce each type. Feel free to bookmark it for future reference.
Strings (str): Representing Text
Since your goal is to build a chatbot, text is the most important type of data you'll work with. In Python, textual data is handled using strings. You can create a string by enclosing text in either single (') or double (") quotes.
For our chatbot, we'll constantly be creating messages. Often, these messages will need to include the value of a variable, like a user's name or a ticket number. The most modern and readable way to do this is with f-strings. You create an f-string by putting an f before the opening quote and then placing your variable names inside curly braces {} directly within the string.
To see how strings and f-strings work, let's go back to the CS50 notes.
Lecture 0 - CS50's Introduction to Programming with Python
This resource explains what strings are and introduces the powerful f-string syntax for embedding variables directly into text.
Read the sections titled Strings and Parameters and Formatting Strings. Pay close attention to the f"hello, {name}" example, as this is a pattern you will use very frequently.
Now, let's dive a little deeper with the Real Python article.
Basic Data Types in Python: A Quick Exploration – Real Python
This part of the article details the different ways to create strings in Python.
In the article, find the section Strings and Characters. Read the subsections on Regular String Literals and F-String Literals.
Numbers (int, float) and Booleans (bool)
Besides text, your chatbot will need to handle other kinds of data.
- Integers (
int) are used for counting things, like the number of messages a user has sent. - Floating-point numbers (
float) are used for measurements, like a customer satisfaction score of 4.5. - Booleans (
bool) are used for states, likeis_resolved = True.
Take a few minutes to read the relevant sections in the Real Python article to understand how these types are represented.
Basic Data Types in Python: A Quick Exploration – Real Python
This reading will solidify your understanding of numeric and boolean types.
In the article, please read the following sections: Integer Numbers: Focus on the introduction. Floating-Point Numbers: Focus on the introduction and literals. Booleans: Read the short introduction up to the literals. Note that True and False must be capitalized.
Explicit Type Conversion
So, what happens when you get data in one type but need it in another? For example, the input() function you've seen always gives you a string, even if the user types a number. If you try to perform math on the string "1982", your program will fail.
You must explicitly convert the type. Python provides simple functions to do this:
int(value)converts a value to an integer.float(value)converts a value to a float.str(value)converts a value to a string.bool(value)converts a value to a boolean.
This is not an abstract problem—it's one of the most common tasks in programming. The following video provides an excellent, practical demonstration of why and how to perform type conversions.
Python for Beginners - Learn Coding with Python in 1 Hour
In this video, Mosh Hamedani masterfully demonstrates the necessity of type conversion. He intentionally runs code that crashes because of a type mismatch and then walks you through fixing it using conversion functions like int() and float().
Watch the two segments that cover type conversion. First, watch the explanation from type conversion, where he calculates a user's age from their input. Then, watch the calculator exercise, which reinforces these concepts and also shows when you might need to convert a number back to a string using str().
Practice Exercise
Let's put all these concepts together. Create a new file named ticket_info.py in your project folder. Write a Python script that does the following:
- Welcomes the user to the support system.
- Asks the user for their name and stores it in a variable.
- Asks the user for the numeric ticket ID (e.g.,
101) and stores it. - Asks the user to confirm if the ticket is new by typing
TrueorFalse. - Crucially, convert the ticket ID to an integer and the "new" status to a boolean. Remember,
input()gives you strings! To convert the string"True"to a boolean, you can compare it:is_new_bool = (is_new_str == "True"). We will cover comparisons in detail in the next lesson. - Finally, print a summary message using an f-string that includes all the collected information and their types, using the
type()function.
Here is some starter code to guide you:
# 1. Welcome message
print("--- Welcome to the Support Ticket System ---")
# 2. Get user's name (this is already a string)
customer_name = input("Please enter your name: ")
# 3. Get ticket ID as a string
ticket_id_str = input("Please enter your numeric ticket ID: ")
# 4. Get ticket status as a string
is_new_str = input("Is this a new ticket? (True/False): ")
# 5. --- YOUR CONVERSION CODE GOES HERE ---
# Convert ticket_id_str to an integer
ticket_id_int = int(ticket_id_str)
# Convert is_new_str to a boolean
is_new_bool = (is_new_str == "True")
# 6. Print the summary
print("\n--- Ticket Information Received ---")
summary = f"Thank you, {customer_name}. Ticket #{ticket_id_int} has been recorded. New status: {is_new_bool}."
print(summary)
# Optional: Print the types to confirm your conversion
print(f"\nType of 'customer_name': {type(customer_name)}")
print(f"Type of 'ticket_id_int': {type(ticket_id_int)}")
print(f"Type of 'is_new_bool': {type(is_new_bool)}")
Run your ticket_info.py script from the terminal. Experiment by entering different values to see how it works.
Conclusion
In this lesson, you've learned the fundamental concepts for representing data in Python. These are the essential building blocks for your journey into programming.
Key takeaways include:
- Variables are named containers used to store values in memory (e.g.,
my_variable = "some_value"). - Values have different data types, such as strings (
str) for text, integers (int) for whole numbers, floats (float) for decimal numbers, and booleans (bool) forTrueorFalse. - F-strings (e.g.,
f"Hello, {name}") are the modern and preferred way to embed variables within strings. - Type conversion is often necessary, especially when handling user input, which is always read as a string. You can use functions like
int(),float(), andstr()to convert between types.
You now know how to store information. In the next lesson, we'll learn how to make your program intelligent by enabling it to make decisions. We will explore how to use comparison and boolean expressions to control which parts of your code run based on the values stored in your variables.