Articles

Variables and Simple Data Types in Python

In this chapter, you’ll learn about the different kinds of data you can work with inyour Python programs. You’ll also learn how to store your data in variables and how to use those variables in your programs.

what really happens when you run hello_world.py

Let’s take a closer look at what Python does when you run hello_world.py. As it turns out, Python does a fair amount of work, even when it runs a simple program:

hello_world.py print("Hello Python world!")

When you run this code, you should see this output:

Hello Python world!

When you run the file hello_world.py, the ending .py indicates that the file is a Python program. Your editor then runs the file through the Python interpreter, which reads through the program and determines what each word in the program means. For example, when the interpreter sees the word print, it prints to the screen whatever is inside the parentheses.

As you write your programs, your editor highlights different parts of your program in different ways. For example, it recognizes that print is the name of a function and displays that word in blue. It recognizes that “Hello Python world!” is not Python code and displays that phrase in orange. This feature is called syntax highlighting and is quite useful as you start to write your own programs.

Variables

Let’s try using a variable in hello_world.py. Add a new line at the beginning of the file, and modify the second line:

message = "Hello Python world!"
print(message)

Run this program to see what happens. You should see the same output you saw previously:

Hello Python world!

We’ve added a variable named message. Every variable holds a value, which is the information associated with that variable. In this case the value is the text “Hello Python world!”

Adding a variable makes a little more work for the Python interpreter. When it processes the first line, it associates the text “Hello Python world!” with the variable message. When it reaches the second line, it prints the value associated with message to the screen.

Let’s expand on this program by modifying hello_world.py to print a second message. Add a blank line to hello_world.py, and then add two new lines of code:

message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)

Now when you run hello_world.py, you should see two lines of output:

Hello Python world!
Hello Python Crash Course world!

You can change the value of a variable in your program at any time, and Python will always keep track of its current value.

In the next part, you will learn the steps required to name and use variables.

This article is an excerpt from A Hands-On, Project-Based Introduction to Programming by Eric Matthes

Reproduced with permission from No Starch Press

Leave a Comment