Continue the series of posts about Python: this new post is about variables and simple data types and constants.
- Hello Python
- Variables and simple data types in Python
- Getting started with Python
- Bitmap message in Python
- Play blackjack with Python
- Bagels a logic game in Python
Starting
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 the following 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 followed by parentheses, 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 one color. It recognizes that “Hello Python world!” is not Python code, and displays that phrase in a different color. 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:
hello_world.py
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 is connected to a value, which is the information associated with that variable. In this case the value is the “Hello Python world!” text.
Adding a variable makes a little more work for the Python interpreter. When it processes the first line, it associates the variable message with the “Hello Python world!” text. 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.
Naming and Using Variables
When you’re using variables in Python, you need to adhere to a few rules and guidelines. Breaking some of these rules will cause errors; other guidelines just help you write code that’s easier to read and understand. Be sure to keep the following rules in mind when working with variables:
- Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. For instance, you can call a variable
message_1
but not1_message
. - Spaces are not allowed in variable names, but underscores can be used to separate words in variable names. For example,
greeting_message
works butgreeting message
will cause errors. - Avoid using Python keywords and function names as variable names. For example, do not use the word
print
as a variable name; Python has reserved it for a particular programmatic purpose. - Variable names should be short but descriptive. For example,
name
is better thann
,student_name
is better thans_n
, andname_length
is better thanlength_of_persons_name
. - Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.
- It can take some practice to learn how to create good variable names, especially as your programs become more interesting and complicated. As you write more programs and start to read through other people’s code, you’ll get better at coming up with meaningful names.
Avoiding Name Errors When Using Variables
Every programmer makes mistakes, and most make mistakes every day. Although good programmers might create errors, they also know how to respond to those errors efficiently. Let’s look at an error you’re likely to make early on and learn how to fix it.
We’ll write some code that generates an error on purpose. Enter the following code, including the misspelled word mesage
:
message = "Hello Python Crash Course reader!"
print(message)
When an error occurs in your program, the Python interpreter does its best to help you figure out where the problem is. The interpreter provides a traceback when a program cannot run successfully. A traceback is a record of where the interpreter ran into trouble when trying to execute your code. Here’s an example of the traceback that Python provides after you’ve accidentally misspelled a variable’s name:
Traceback (most recent call last):
❶ File "hello_world.py", line 2, in
❷ print(mesage)
^^^^^^
❸ NameError: name 'mesage' is not defined. Did you mean: 'message'?
The output reports that an error occurs in line 2 of the file hello_world.py ❶. The interpreter shows this line ❷ to help us spot the error quickly and tells us what kind of error it found ❸. In this case it found a name error and reports that the variable being printed, mesage
, has not been defined. Python can’t identify the variable name provided. A name error usually means we either forgot to set a variable’s value before using it, or we made a spelling mistake when entering the variable’s name. If Python finds a variable name that’s similar to the one it doesn’t recognize, it will ask if that’s the name you meant to use.
In this example we omitted the letter s in the variable name message
in the second line. The Python interpreter doesn’t spellcheck your code, but it does ensure that variable names are spelled consistently. For example, watch what happens when we spell message incorrectly in the line that defines the variable:
mesage = "Hello Python Crash Course reader!"
print(mesage)
In this case, the program runs successfully!
Hello Python Crash Course reader!
The variable names match, so Python sees no issue. Programming languages are strict, but they disregard good and bad spelling. As a result, you don’t need to consider English spelling and grammar rules when you’re trying to create variable names and writing code.
Many programming errors are simple, single-character typos in one line of a program. If you find yourself spending a long time searching for one of these errors, know that you’re in good company. Many experienced and talented programmers spend hours hunting down these kinds of tiny errors. Try to laugh about it and move on, knowing it will happen frequently throughout your programming life.
Variables Are Labels
Variables are often described as boxes you can store values in. This idea can be helpful the first few times you use a variable, but it isn’t an accurate way to describe how variables are represented internally in Python. It’s much better to think of variables as labels that you can assign to values. You can also say that a variable references a certain value.
This distinction probably won’t matter much in your initial programs, but it’s worth learning earlier rather than later. At some point, you’ll see unexpected behavior from a variable, and an accurate understanding of how variables work will help you identify what’s happening in your code.
Strings
Because most programs define and gather some sort of data and then do something useful with it, it helps to classify different types of data. The first data type we’ll look at is the string. Strings are quite simple at first glance, but you can use them in many different ways.
A string is a series of characters. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your strings like this:
"This is a string."
'This is also a string.'
This flexibility allows you to use quotes and apostrophes within your strings:
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."
Let’s explore some of the ways you can use strings.
Changing Case in a String with Methods
One of the simplest tasks you can do with strings is change the case of the words in a string. Look at the following code, and try to determine what’s happening:
name.py
name = "ada lovelace"
print(name.title())
Save this file as name.py and then run it. You should see this output:
Ada Lovelace
In this example, the variable name
refers to the lowercase string "ada lovelace"
. The method title()
appears after the variable in the print()
call. A method is an action that Python can perform on a piece of data. The dot (.) after name in name.title()
tells Python to make the title()
method act on the variable name. Every method is followed by a set of parentheses, because methods often need additional information to do their work. That information is provided inside the parentheses. The title() function doesn’t need any additional information, so its parentheses are empty.
The title()
method changes each word to title case, where each word begins with a capital letter. This is useful because you’ll often want to think of a name as a piece of information. For example, you might want your program to recognize the input values Ada
, ADA
, and ada
as the same name, and display all of them as Ada.
Several other useful methods are available for dealing with case as well. For example, you can change a string to all uppercase or all lowercase letters like this:
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
This will display the following:
ADA LOVELACE
ada lovelace
The lower()
method is particularly useful for storing data. You typically won’t want to trust the capitalization that your users provide, so you’ll convert strings to lowercase before storing them. Then when you want to display the information, you’ll use the case that makes the most sense for each string.
Using Variables in Strings
In some situations, you’ll want to use a variable’s value inside a string. For example, you might want to use two variables to represent a first name and a last name, respectively, and then combine those values to display someone’s full name:
full_name.py
first_name = "ada"
last_name = "lovelace"
❶ full_name = f"{first_name} {last_name}"
print(full_name)
To insert a variable’s value into a string, place the letter f immediately before the opening quotation mark ❶. Put braces around the name or names of any variable you want to use inside the string. Python will replace each variable with its value when the string is displayed.
These strings are called f-strings. The f
is for format, because Python formats the string by replacing the name of any variable in braces with its value. The output from the previous code is:
ada lovelace
You can do a lot with f-strings
. For example, you can use f-strings to compose complete messages using the information associated with a variable, as shown here:
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
❶ print(f"Hello, {full_name.title()}!")
The full name is used in a sentence that greets the user ❶, and the title() method changes the name to title case. This code returns a simple but nicely formatted greeting:
Hello, Ada Lovelace!
You can also use f-strings to compose a message, and then assign the entire message to a variable:
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
❶ message = f"Hello, {full_name.title()}!"
❷ print(message)
This code displays the message Hello, Ada Lovelace! as well, but by assigning the message to a variable ❶ we make the final print() call much simpler ❷.
Adding Whitespace to Strings with Tabs or Newlines
In programming, whitespace refers to any nonprinting characters, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read.
To add a tab to your text, use the character combination \t:
>>> print("Python")
Python
>>> print("\tPython")
Python
To add a newline in a string, use the character combination \n
:
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
Newlines and tabs will be very useful in the next two chapters, when you start to produce many lines of output from just a few lines of code.
Stripping Whitespace
Extra whitespace can be confusing in your programs. To programmers, 'python'
and 'python '
look pretty much the same. But to a program, they are two different strings. Python detects the extra space in 'python '
and considers it significant unless you tell it otherwise.
It’s important to think about whitespace, because often you’ll want to compare two strings to determine whether they are the same. For example, one important instance might involve checking people’s usernames when they log in to a website. Extra whitespace can be confusing in much simpler situations as well. Fortunately, Python makes it easy to eliminate extra whitespace from data that people enter.
Python can look for extra whitespace on the right and left sides of a string. To ensure that no whitespace exists at the right side of a string, use the rstrip()
method:
❶ >>> favorite_language = 'python '
❷ >>> favorite_language
'python '
❸ >>> favorite_language.rstrip()
'python'
❹ >>> favorite_language
'python '
The value associated with favorite_language
❶ contains extra whitespace at the end of the string. When you ask Python for this value in a terminal session, you can see the space at the end of the value ❷. When the rstrip()
method acts on the variable favorite_language
❸, this extra space is removed. However, it is only removed temporarily. If you ask for the value of favorite_language again, the string looks the same as when it was entered, including the extra whitespace ❹.
To remove the whitespace from the string permanently, you have to associate the stripped value with the variable name:
favorite_language = 'python '
❶ >>> favorite_language = favorite_language.rstrip()
favorite_language
'python'
To remove the whitespace from the string, you strip the whitespace from the right side of the string and then associate this new value with the original variable ❶. Changing a variable’s value is done often in programming. This is how a variable’s value can be updated as a program is executed or in response to user input.
You can also strip whitespace from the left side of a string using the lstrip()
method, or from both sides at once using strip():
❶ >>> favorite_language = ' python '
❷ >>> favorite_language.rstrip()
' python'
❸ >>> favorite_language.lstrip()
'python '
❹ >>> favorite_language.strip()
'python'
In this example, we start with a value that has whitespace at the beginning and the end ❶. We then remove the extra space from the right side ❷, from the left side ❸, and from both sides ❹. Experimenting with these stripping functions can help you become familiar with manipulating strings. In the real world, these stripping functions are used most often to clean up user input before it’s stored in a program.
Removing Prefixes
When working with strings, another common task is to remove a prefix. Consider a URL with the common prefix https://. We want to remove this prefix, so we can focus on just the part of the URL that users need to enter into an address bar. Here’s how to do that:
nostarch_url = 'https://nostarch.com'
nostarch_url.removeprefix('https://')
'nostarch.com'
Enter the name of the variable followed by a dot, and then the method removeprefix()
. Inside the parentheses, enter the prefix you want to remove from the original string.
Like the methods for removing whitespace, removeprefix() leaves the original string unchanged. If you want to keep the new value with the prefix removed, either reassign it to the original variable or assign it to a new variable:
simple_url = nostarch_url.removeprefix('https://')
When you see a URL in an address bar and the https://
part isn’t shown, the browser is probably using a method like removeprefix() behind the scenes.
Avoiding Syntax Errors with Strings
One kind of error that you might see with some regularity is a syntax error. A syntax error occurs when Python doesn’t recognize a section of your program as valid Python code. For example, if you use an apostrophe within single quotes, you’ll produce an error. This happens because Python interprets everything between the first single quote and the apostrophe as a string. It then tries to interpret the rest of the text as Python code, which causes errors.
Here’s how to use single and double quotes correctly. Save this program as apostrophe.py and then run it:
apostrophe.py
message = "One of Python's strengths is its diverse community."
print(message)
The apostrophe appears inside a set of double quotes, so the Python interpreter has no trouble reading the string correctly:
One of Python's strengths is its diverse community.
However, if you use single quotes, Python can’t identify where the string should end:
message = 'One of Python's strengths is its diverse community.'
print(message)
You’ll see the following output:
File "apostrophe.py", line 1
message = 'One of Python's strengths is its diverse community.'
❶ ^
SyntaxError: unterminated string literal (detected at line 1)
In the output you can see that the error occurs right after the final single quote ❶. This syntax error indicates that the interpreter doesn’t recognize something in the code as valid Python code, and it thinks the problem might be a string that’s not quoted correctly. Errors can come from a variety of sources, and I’ll point out some common ones as they arise. You might see syntax errors often as you learn to write proper Python code. Syntax errors are also the least specific kind of error, so they can be difficult and frustrating to identify and correct.
Numbers
Numbers are used quite often in programming to keep score in games, represent data in visualizations, store information in web applications, and so on. Python treats numbers in several different ways, depending on how they’re being used. Let’s first look at how Python manages integers, because they’re the simplest to work with.
Integers
You can add (+
), subtract (-
), multiply (*
), and divide (/
) integers in Python.
>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5
In a terminal session, Python simply returns the result of the operation. Python uses two multiplication symbols to represent exponents:
>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000
Python supports the order of operations too, so you can use multiple operations in one expression. You can also use parentheses to modify the order of operations so Python can evaluate your expression in the order you specify. For example:
>>> 2 + 3*4
14
>>> (2 + 3) * 4
20
The spacing in these examples has no effect on how Python evaluates the expressions; it simply helps you more quickly spot the operations that have priority when you’re reading through the code.
Floats
Python calls any number with a decimal point a float. This term is used in most programming languages, and it refers to the fact that a decimal point can appear at any position in a number. Every programming language must be carefully designed to properly manage decimal numbers so numbers behave appropriately, no matter where the decimal point appears.
For the most part, you can use floats without worrying about how they behave. Simply enter the numbers you want to use, and Python will most likely do what you expect:
>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.2
0.4
>>> 2 * 0.1
0.2
>>> 2 * 0.2
0.4
However, be aware that you can sometimes get an arbitrary number of decimal places in your answer
>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004
This happens in all languages and is of little concern. Python tries to find a way to represent the result as precisely as possible, which is sometimes difficult given how computers have to represent numbers internally. Just ignore the extra decimal places for now.
Integers and Floats
When you divide any two numbers, even if they are integers that result in a whole number, you’ll always get a float:
>>> 4/2
2.0
If you mix an integer and a float in any other operation, you’ll get a float as well
>>> 1 + 2.0
3.0
>>> 2 * 3.0
6.0
>>> 3.0 ** 2
9.0
Python defaults to a float in any operation that uses a float, even if the output is a whole number.
Underscores in Numbers
When you’re writing long numbers, you can group digits using underscores to make large numbers more readable:
>>> universe_age = 14_000_000_000
When you print a number that was defined using underscores, Python prints only the digits:
>>> print(universe_age)
14000000000
Python ignores the underscores when storing these kinds of values. Even if you don’t group the digits in threes, the value will still be unaffected. To Python, 1000 is the same as 1_000, which is the same as 10_00. This feature works for both integers and floats.
Multiple Assignment
You can assign values to more than one variable using just a single line of code. This can help shorten your programs and make them easier to read; you’ll use this technique most often when initializing a set of numbers.
For example, here’s how you can initialize the variables x, y, and z to zero:
>>> x, y, z = 0, 0, 0
You need to separate the variable names with commas, and do the same with the values, and Python will assign each value to its respective variable. As long as the number of values matches the number of variables, Python will match them up correctly.
Constants
A constant is a variable whose value stays the same throughout the life of a program. Python doesn’t have built-in constant types, but Python programmers use all capital letters to indicate a variable should be treated as a constant and never be changed:
MAX_CONNECTIONS = 5000
When you want to treat a variable as a constant in your code, write the name of the variable in all capital letters.