Chapter 2: Variables and Simple Data Types

Source: Python Crash Course, 3rd Edition by Eric Matthes

In this chapter you’ll learn about the different kinds of data you can work with in your Python programs. You’ll also learn how to use variables to represent data 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. 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:

Hello Python world!

When you run hello_world.py, the .py extension indicates that the file is a Python program. Your editor runs the file through the Python interpreter, which reads through the program and determines what each word 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 in different ways. It recognizes that print() is a function name and displays it in one color, and it recognizes that "Hello Python world!" is not Python code and displays it in a different color. This feature is called syntax highlighting and is quite useful as you start writing 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 as before:

Hello Python world!

We’ve added a variable named message. Every variable is connected to a value β€” 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 variable message with the text "Hello Python world!". When it reaches the second line, it prints the value associated with message to the screen.

Let’s expand on this program by printing 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 at any time, and Python will always keep track of its current value.

Naming and Using Variables

When using variables in Python, you need to adhere to a few rules and guidelines. Breaking some of these rules will cause errors; others just help you write code that’s easier to read and understand. 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, message_1 is valid but 1_message is not.

  • Spaces are not allowed in variable names. Use underscores to separate words β€” greeting_message works, but greeting message will cause errors.

  • Avoid using Python keywords and function names as variable names. For example, do not use print as a variable name; Python has reserved it for a particular purpose. (See Python Keywords and Built-in Functions on page 466.)

  • Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name.

  • Be careful when using the lowercase letter l and the uppercase letter O because they can 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 read through other people’s code, you’ll get better at coming up with meaningful names.

The Python variables you’re using at this point should be lowercase. You won’t get errors if you use uppercase letters, but uppercase letters in variable names have special meanings that we’ll discuss in later chapters.

Avoiding Name Errors When Using Variables

Every programmer makes mistakes β€” and most make mistakes every day. Good programmers 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(mesage)

When an error occurs, the Python interpreter provides a traceback β€” a record of where the interpreter ran into trouble when trying to execute your code. Here’s an example of the traceback Python produces after you accidentally misspell a variable’s name:

Traceback (most recent call last):
  File "hello_world.py", line 2, in <module> (1)
    print(mesage)                             (2)
          ^^^^^^
NameError: name 'mesage' is not defined. Did you mean: 'message'? (3)
1 The error occurs in line 2 of hello_world.py.
2 The interpreter shows this line to help you spot the error quickly.
3 The error kind is reported β€” here a NameError for an undefined variable name.

A name error usually means you either forgot to set a variable’s value before using it, or you made a spelling mistake when entering the variable’s name. If Python finds a variable name similar to the one it doesn’t recognize, it will suggest what you may have meant.

In this example, the letter s was omitted from 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 creating variable names.

Many programming errors are simple, single-character typos in one line of a program. Many experienced programmers spend hours hunting down these kinds of tiny errors β€” try to laugh about it and move on.

Variables Are Labels

Variables are often described as boxes you can store values in. This idea can be helpful at first, 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.

The best way to understand new programming concepts is to try using them in your programs. If you get stuck on an exercise, try doing something else for a while. If you’re still stuck, review the relevant part of that chapter. If you still need help, see the suggestions in Appendix C.

Try It Yourself

Write a separate program for each exercise. Save each program with a filename that follows standard Python conventions, using lowercase letters and underscores, such as simple_message.py and simple_messages.py.

2-1. Simple Message: Assign a message to a variable, and then print that message.

2-2. Simple Messages: Assign a message to a variable, and print that message. Then change the value of the variable to a new message, and print the new message.

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:

"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. 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:

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 treat a name as a piece of information β€” for example, you might want your program to recognize 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. For example, you can change a string to all uppercase or all lowercase:

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

This will display:

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}" (1)
print(full_name)
1 To insert a variable’s value into a string, place the letter f immediately before the opening quotation mark. Put braces around the name 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 them to compose complete messages using the information associated with a variable:

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!") (1)
1 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 assign an f-string to a variable to make the final print() call simpler:

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
message = f"Hello, {full_name.title()}!" (1)
print(message)                           (2)
1 Assigning the message to a variable…​
2 …​makes 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

You can also combine tabs and newlines in a single string. The string "\n\t" tells Python to move to a new line, and start the next line with a tab. The following example uses a one-line string to generate four lines of output:

>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
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. 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 '  (1)
>>> favorite_language              (2)
'python '
>>> favorite_language.rstrip()     (3)
'python'
>>> favorite_language              (4)
'python '
1 The value contains extra whitespace at the end of the string.
2 You can see the trailing space when you ask Python for this value.
3 rstrip() removes the extra space.
4 The removal is only temporary β€” the original value is unchanged.

To remove the whitespace permanently, you have to associate the stripped value back with the variable name:

>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip() (1)
>>> favorite_language
'python'
1 Strip the whitespace from the right side and associate the new value with the original variable.

You can also strip whitespace from the left side using lstrip(), or from both sides at once using strip():

>>> favorite_language = ' python '  (1)
>>> favorite_language.rstrip()      (2)
' python'
>>> favorite_language.lstrip()      (3)
'python'
>>> favorite_language.strip()       (4)
'python'
1 Start with whitespace at both the beginning and the end.
2 Remove extra space from the right side.
3 Remove extra space from the left side.
4 Remove extra space from both sides.

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

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 whitespace-stripping methods, 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

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. Python interprets everything between the first single quote and the apostrophe as a string, 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.'
                                                                   ^ (1)
SyntaxError: unterminated string literal (detected at line 1)
1 The error occurs right after the final single quote.

Syntax errors are the least specific kind of error, so they can be difficult and frustrating to identify and correct. If you get stuck on a particularly stubborn error, see the suggestions in Appendix C.

Your editor’s syntax highlighting feature should help you spot some syntax errors quickly as you write your programs. If you see Python code highlighted as if it’s English, or English highlighted as if it’s Python code, you probably have a mismatched quotation mark somewhere in your file.

Try It Yourself

Save each of the following exercises as a separate file, with a name like name_cases.py. If you get stuck, take a break or see the suggestions in Appendix C.

2-3. Personal Message: Use a variable to represent a person’s name, and print a message to that person. Your message should be simple, such as, Hello Eric, would you like to learn some Python today?

2-4. Name Cases: Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case.

2-5. Famous Quote: Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:

Albert Einstein once said, "A person who never made a mistake never tried anything new."

2-6. Famous Quote 2: Repeat Exercise 2-5, but this time represent the famous person’s name using a variable called famous_person. Then compose your message and represent it with a new variable called message. Print your message.

2-7. Stripping Names: Use a variable to represent a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, \t and \n, at least once. Print the name once so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().

2-8. File Extensions: Python has a removesuffix() method that works exactly like removeprefix(). Assign the value 'python_notes.txt' to a variable called filename. Then use the removesuffix() method to display the filename without the file extension, like some file browsers do.

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, so you can use multiple operations in one expression. You can also use parentheses to modify the order of operations:

>>> 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 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 they 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; you’ll learn ways to deal with them when you need to in the projects in Part II.

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:

>>> 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.

Try It Yourself

2-9. Number Eight: Write addition, subtraction, multiplication, and division operations that each result in the number 8. Be sure to enclose your operations in print() calls to see the results. You should create four lines that look like this:

print(5 + 3)

Your output should be four lines, with the number 8 appearing once on each line.

2-10. Favorite Number: Use a variable to represent your favorite number. Then, using that variable, create a message that reveals your favorite number. Print that message.

Comments

Comments are an extremely useful feature in most programming languages. As your programs become longer and more complicated, you should add notes within your programs that describe your overall approach to the problem you’re solving. A comment allows you to write notes in your spoken language, within your programs.

How Do You Write Comments?

In Python, the hash mark (#) indicates a comment. Anything following a hash mark in your code is ignored by the Python interpreter:

comment.py
# Say hello to everyone.
print("Hello Python people!")

Python ignores the first line and executes the second line:

Hello Python people!

What Kinds of Comments Should You Write?

The main reason to write comments is to explain what your code is supposed to do and how you are making it work. When you’re in the middle of working on a project, you understand how all the pieces fit together. But when you return to a project after some time away, you’ll likely have forgotten some of the details. Writing good comments can save you time by summarizing your overall approach clearly.

If you want to become a professional programmer or collaborate with other programmers, you should write meaningful comments. Today, most software is written collaboratively, and skilled programmers expect to see comments in code. Writing clear, concise comments is one of the most beneficial habits you can form as a new programmer.

When deciding whether to write a comment, ask yourself if you had to consider several approaches before coming up with a reasonable solution; if so, write a comment about your solution. It’s much easier to delete extra comments later than to go back and write comments for a sparsely commented program.

Try It Yourself

2-11. Adding Comments: Choose two of the programs you’ve written, and add at least one comment to each. If you don’t have anything specific to write because your programs are too simple at this point, just add your name and the current date at the top of each program file. Then write one sentence describing what the program does.

The Zen of Python

Experienced Python programmers will encourage you to avoid complexity and aim for simplicity whenever possible. The Python community’s philosophy is contained in The Zen of Python by Tim Peters. You can access this brief set of principles by entering import this into your interpreter:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Python programmers embrace the notion that code can be beautiful and elegant. As you learn more about Python and use it to write more code, someone might look over your shoulder one day and say, "Wow, that’s some beautiful code!"

Simple is better than complex.
If you have a choice between a simple and a complex solution, and both work, use the simple solution. Your code will be easier to maintain, and it will be easier for you and others to build on later.

Complex is better than complicated.
Real life is messy, and sometimes a simple solution to a problem is unattainable. In that case, use the simplest solution that works.

Readability counts.
Even when your code is complex, aim to make it readable. When you’re working on a project with complex coding, focus on writing informative comments for that code.

There should be one β€” and preferably only one β€” obvious way to do it.
If two Python programmers are asked to solve the same problem, they should come up with fairly compatible solutions. There is plenty of room for creativity in programming β€” however, much of programming consists of using small, common approaches to simple situations within a larger, more creative project. The nuts and bolts of your programs should make sense to other Python programmers.

Now is better than never.
You could spend the rest of your life learning all the intricacies of Python and of programming in general, but then you’d never complete any projects. Don’t try to write perfect code; write code that works, and then decide whether to improve your code for that project or move on to something new.

As you continue to the next chapter and start digging into more involved topics, try to keep this philosophy of simplicity and clarity in mind. Experienced programmers will respect your code more and will be happy to give you feedback and collaborate with you on interesting projects.

Try It Yourself

2-12. Zen of Python: Enter import this into a Python terminal session and skim through the additional principles.

Summary

In this chapter you learned how to work with variables. You learned to use descriptive variable names and resolve name errors and syntax errors when they arise. You learned what strings are and how to display them using lowercase, uppercase, and title case. You started using whitespace to organize output neatly, and you learned how to remove unneeded elements from a string. You started working with integers and floats, and you learned some of the ways you can work with numerical data. You also learned to write explanatory comments to make your code easier for you and others to read. Finally, you read about the philosophy of keeping your code as simple as possible, whenever possible.

In Chapter 3, you’ll learn how to store collections of information in data structures called lists. You’ll also learn how to work through a list, manipulating any information in that list.

Applied Exercises: Ch 2 β€” Variables and Simple Data Types

These exercises cover the same concepts as the chapter but use context from real infrastructure, network security, and language learning work. Save each as a separate .py file using lowercase and underscores, e.g. ise_node_label.py.

Domus Digitalis / Homelab

D2-1. Node Labels: Assign the hostname of one of your KVM hypervisors to a variable called node. Print a message that reads: Connecting to node: kvm-01.

D2-2. VLAN Inventory: Assign a VLAN name and VLAN ID to two separate variables. Use an f-string to print a message like: VLAN 100 β€” INFRA. Then change the values to a second VLAN and print again.

D2-3. Stripping Device Input: Assign a device hostname with leading and trailing whitespace (e.g., ' vyos-01 ') to a variable. Print the raw value so the whitespace is visible. Then print the result of lstrip(), rstrip(), and strip() on separate lines.

D2-4. Interface Prefix: Assign the string 'eth:eth0' to a variable called iface. Use removeprefix() to strip the 'eth:' prefix and print just the interface name.

D2-5. BGP Math: Your BGP design uses AS 65000 for VyOS and AS 65001 for Cilium. Assign each AS number to a variable. Print the sum, the difference, and confirm they are not equal using a print statement. Use underscores in any numbers over 1000 for readability.

CHLA / ISE / Network Security

C2-1. ISE Node Message: Assign the hostname 'ise-02' to a variable called ise_node. Print a message using an f-string that reads: Active ISE node: ISE-02 β€” use .upper() on the variable so the hostname is displayed in uppercase.

C2-2. Policy Name Formatting: Assign a policy set name in mixed case (e.g., ' 802.1X Wired Policy ') to a variable. Use strip() to clean it, then title() to normalize the case. Print both the raw and cleaned values.

C2-3. URL Prefix Removal: Assign the string 'https://ise-02.chla.usc.edu/admin' to a variable called ise_url. Use removeprefix() to remove 'https://' and print the result.

C2-4. Syslog Constants: Define two constants representing syslog severity levels used in your Monad pipelines: CRITICAL_SEVERITY and ARCHIVE_SEVERITY. Assign them integer values (e.g., 2 and 6). Print a message that clearly labels each one.

C2-5. Name Error Practice: Write a short script that defines a variable endpoint_group but accidentally prints endpoit_group. Observe the traceback. Then fix the typo and confirm the output is correct. Add a comment above each line explaining what it does.

General Sysadmin / Linux

L2-1. Service Status Message: Assign a service name (e.g., 'wazuh-manager') and a status (e.g., 'active') to two variables. Use an f-string to print: Service wazuh-manager is active.

L2-2. Path Prefix: Assign the string '/mnt/user-data/uploads/report.pdf' to a variable called full_path. Use removeprefix() to strip '/mnt/user-data/uploads/' and print just the filename.

L2-3. Storage Math: Your Synology NAS has 8 drives at 8TB each in RAID6, giving usable capacity of approximately 48TB. Assign the number of drives, drive size in TB, and usable capacity each to a variable. Use underscores where appropriate for large numbers. Print a formatted summary using f-strings.

L2-4. Multiple Assignment: Use a single line to assign your three primary DNS server IPs to variables primary, secondary, and tertiary. Print each on its own line with a label.

Spanish / DELE C2

E2-1. Vocabulary Variable: Assign a Spanish word you’ve encountered in Don Quijote to a variable called palabra, and its English definition to definicion. Use an f-string to print: palabra: <word> β€” definicion: <definition>.

E2-2. Chapter Tracker: Assign the current chapter number of Don Quijote you’re reading to a variable called capitulo_actual. Print a message like: Leyendo el capΓ­tulo 30 de Don Quijote.

E2-3. Case Normalization: Assign a Spanish verb in mixed or inconsistent case (e.g., 'hAbLaR') to a variable called verbo. Use .lower() to normalize it, then .title() to display it in title case. Print both results.

E2-4. Stripping Input: Assign a Spanish phrase with extra whitespace on both sides (e.g., ' en un lugar de la Mancha ') to a variable. Print the phrase with whitespace visible, then print the stripped version using strip().

E2-5. DELE Level Constant: Define a constant called DELE_TARGET and assign it the string 'C2'. Print a motivational message using an f-string that incorporates the constant.