In this chapter, you will start learning about the variables and strings. You can use it in your Python programs. You will also see how to use variables to store and represent this data in your code. But before we move forward, let’s first see what really happens when you run your first program.
What Really Happens When You Run hello_world.py
Let’s take a closer look at what Python does when you run your first program. Even though the program is very short, Python still performs several steps in the background.
Here is the code again:
print("Hello Python world!")
When you run this file, you see the output:
Hello Python world!
This looks simple, but let’s break down exactly what happens.
Role of.py
Extension
When you save your program as hello_world.py, the .py extension tells your computer that this is a Python file.
Your editor (like VS Code) then runs this file through the Python interpreter. The interpreter is the tool that reads your program and tells the computer what to do.
How Interpreter Reads Your Program
The Python interpreter reads your file from top to bottom, line by line. It checks what each word and symbol means.
- When it sees the word print, it recognizes this as a function.
- A function is a command that asks Python to do a specific task. In this case, the task is to show something on the screen.
- The parentheses
()
tell Python where the information for the function starts and ends. - Inside the parentheses, the text
"Hello Python world!"
is written. This is not code. It is plain text. In Python, plain text like this is called a string. - The interpreter then sends this string to the screen, and you see the output.
So even a single line of code goes through a clear process: Python reads the command, understands what it means, and then shows the result.
Syntax Highlighting in Your Editor
When you write programs in an editor such as VS Code, you may notice that different parts of your code appear in different colors. This is called syntax highlighting.
- The word
print
is shown in one color because the editor recognizes it as the name of a function. - The string
"Hello Python world!"
appears in another color because it is plain text, not Python code.
Syntax highlighting is very helpful. It makes your code easier to read. It also helps you notice mistakes, such as missing quotation marks or parentheses, because the colors will look different if something is wrong.
Variables in Python
Now that you know how to run a simple program. Let’s make it more powerful by using variables. A variable is like a box that stores information. You can give the box a name, put some data inside it, and then use it later in your program.
Using a Variable in hello_world.py
Open your hello_world.py file. Add a new line at the beginning and change your code to this:
message = "Hello Python world!"
print(message)
When you run the program, the output looks the same as before:
Hello Python world!
So, what happened here?
- We created a variable named message.
- This variable is connected to a value. The value in this case is the string
"Hello Python world!"
. - When Python reads the first line, it stores the text inside the variable message.
- When Python reaches the second line, it looks inside the variable and prints its value to the screen.
The output is the same, but Python is now doing a little more work behind the scenes. It keeps track of the variable and its value.
Changing the Value of a Variable
One of the most useful things about variables is that you can change their values at any time. Let’s try it. Update your program so it looks like this:
message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)
Notice that we added a blank line in the middle just to make the program easier to read.
Now, when you run the program, you see two lines of output:
Hello Python world!
Hello Python Crash Course world!
Here’s what happened step by step:
- Python reads the first line and stores
"Hello Python world!"
in the variable message. - The second line prints the value of message, so you see the first output.
- The third line changes the value of message to
"Hello Python Crash Course world!"
. - The fourth line prints the new value of message, so you see the second output.
Naming and Using Variables
When you create variables in Python, you must follow certain rules. Some rules are strict, and if you break them, Python will show you an error. Other rules are more like guidelines that help make your code easier to read and understand.
Let’s go through these rules one by one.
Rules for Variable Names
- Allowed characters
A variable name can only contain letters, numbers, and underscores (_
).- It can start with a letter or an underscore, but it cannot start with a number.
- Example:
message_1
is valid, but1_message
will give an error.
- No spaces in names
Variable names cannot contain spaces.- If you want to separate words, use an underscore.
- Example:
greeting_message
works, butgreeting message
will cause an error.
- Do not use Python keywords or functions
Python has certain words reserved for its own use, such asprint
,for
,if
, etc. You cannot use these as variable names.- Example: Don’t name a variable
print
, because Python already uses this word for printing output.
- Example: Don’t name a variable
- Make names descriptive
Variable names should be short but also meaningful.- Example:
name
is better thann
.
student_name
is clearer thans_n
.
name_length
is better thanlength_of_persons_name
(too long).
- Example:
- Avoid confusion with letters and numbers
Be careful with the lowercase letter l and the uppercase letter O, because they look very similar to the numbers 1 and 0.
Note: For now, you should write variable names in lowercase letters. Python does allow uppercase letters in variable names, but uppercase often has special meanings in programming. We will learn about those in later chapters.
Avoiding Name Errors When Using Variables
Every programmer makes mistakes. In fact, most programmers make mistakes almost every day. But the difference between a beginner and an experienced programmer is how they deal with these mistakes. Good programmers still create errors, but they know how to fix them quickly.
Let’s look at a very common error you will face in the beginning: a NameError. We’ll even write some code that creates this error on purpose.
message = "Hello Python Crash Course reader!"
print(mesage)
Notice the small spelling mistake. The variable name message
is written correctly in the first line, but in the second line it is misspelled as mesage
(missing the letter s).
What Happens When Python Finds an Error
When an error occurs, Python does its best to guide you. It shows a traceback, which is a report of where the program went wrong.
Here’s what the traceback looks like for the above program:
Traceback (most recent call last):
❶ File "hello_world.py", line 2, in <module>
❷ print(mesage)
^^^^^^
❸ NameError: name 'mesage' is not defined. Did you mean: 'message'?
Let’s break this down:
- At ❶, Python tells us the error is in line 2 of the file
hello_world.py
. - At ❷, it shows the exact line where the problem happened.
- At ❸, Python explains the error. It says:
NameError: name 'mesage' is not defined.
This means Python does not recognize the word mesage
because no variable with this name exists. Interestingly, Python also tries to help. It guesses that maybe you meant message
and even suggests it.
Why Name Errors Happen
A NameError usually happens for two reasons:
- You forgot to set a variable’s value before using it.
- You made a spelling mistake in the variable’s name.
In our example, the problem was a missing letter.
Python is Strict, Not a Spellchecker
Now look at this code:
mesage = "Hello Python Course reader!"
print(mesage)
This time, the program runs successfully:
Hello Python Course reader!
Why? Because both the variable definition and the print statement use the same spelling mesage
. Python doesn’t care that mesage
is a misspelling in English. It only cares that the names match exactly.
So, programming languages are strict, but they do not check for “good spelling.” They only check for consistency in names.
Variables Are Labels
Many books say that variables are like boxes where you can store values. This picture can be helpful when you are just starting out. It gives you a simple way to imagine what a variable does.
But in Python, this idea is not completely correct. Variables are not really boxes that hold values. Instead, it’s better to think of variables as labels.
When you create a variable, you are actually attaching a label to a value. You can also say that the variable is a reference to a value.
Why This Matters
In your first few programs, this difference may not seem important. You will still get your code to work whether you imagine variables as boxes or labels.
But later, when your programs become more complex, you might see behavior that feels strange or unexpected. At that moment, having the right picture in your mind will help. If you understand that variables are labels pointing to values, you will be able to figure out why something is happening in your code.
Note: The best way to understand new programming ideas is to use them in practice. Theory is useful, but practice is where real learning happens.
Try It Yourself
Now it’s your turn to practice. Hands-on coding is the best way to understand how Python works. You should write a separate program for each of these small exercises.
When saving your files, follow Python’s naming rules. Always use lowercase letters and separate words with underscores. For example:
simple_message.py
simple_messages.py
This keeps your code clean and professional.
1. Simple Message
In this task, you will:
- Assign a message to a variable.
- Print that message.
Example code:
# simple_message.py
message = "Hello, this is my first Python message!"
print(message)
When you run this program, it shows the text you stored in the variable.
2. Simple Messages
In this task, you will:
- Assign a message to a variable.
- Print that message.
- Change the value of the same variable.
- Print the new message.
Example code:
# simple_messages.py
message = "Python is fun to learn!"
print(message)
message = "I am learning how to change variables."
print(message)
When you run this program, you see two outputs. The first one is the original message. The second one is the updated message after changing the variable’s value.
Strings in Python
In Python, you work with different kinds of data. To use them properly, you need to classify them into types. The first data type we study is the string.
Strings look very simple at first, but they are extremely powerful. You will use them in many programs, from printing text to storing user input.
What is a String?
A string is a series of characters.
- Characters can be letters, numbers, spaces, or symbols.
- In Python, anything you put inside quotes becomes a string.
For example:
"This is a string."
'This is also a string.'
Both single quotes (' '
) and double quotes (" "
) work the same way.
Two Types of Quotes
Python gives you flexibility with quotes. This makes it easy to include apostrophes or quotation marks inside your strings without breaking them.
Examples:
'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."
Notice what happens:
- In the first example, the outer quotes are single (
' '
), so the double quotes inside work fine. - In the second example, the outer quotes are double (
" "
), so the single quotes inside are safe. - In the third example, you see how apostrophes work naturally inside double quotes.
This flexibility allows you to write clean and natural text without confusion.
Why Strings Matter
Strings may look small, but they are everywhere in Python.
- You use them to display messages.
- You use them to store names, input, and text.
- You even use them to work with data from files and websites.
That’s why strings are one of the first building blocks in your programming journey.
Changing Case in a String with Methods
One of the most common tasks with strings is changing the case of words. Python gives you simple tools, called methods to do this quickly. Let’s see an example.
Example: Title Case
Create a file called name.py and write this code:
name = "ada lovelace"
print(name.title())
When you run this program, you get the output:
Ada Lovelace
Here’s what happens step by step:
- The variable name stores the string
"ada lovelace"
. - The method title() appears after the variable in
name.title()
. - The dot ( . ) tells Python to apply the method to the variable.
- A method is simply an action that Python can perform on data.
- Since title() does not need extra information, the parentheses are empty.
The title() method capitalizes each word. That’s why "ada lovelace"
becomes "Ada Lovelace"
.
This is useful because in programs you often treat names as important data. For example, whether a user types Ada, ADA, or ada, your program can display all of them in the same clean format: Ada.
Other Case Methods
Python also gives you methods to convert strings fully to uppercase or lowercase.
name = "Ada Lovelace"
print(name.upper())
print(name.lower())
This code produces:
ADA LOVELACE
ada lovelace
- upper() makes the string all uppercase.
- lower() makes the string all lowercase.
The lower() method is beneficial when you need to store data. You don’t want to rely on how users capitalize their input. For example, one person may type John, another john, and another JOHN. If you store all input in lowercase, you can keep your data consistent. Later, when you display the information, you can format it in the style you want.
Using Variables in Strings
Sometimes, you don’t just want to print plain text. You want to include a variable’s value inside a string. For example, you may store a person’s first name and last name in two variables, and then combine them to display the full name.
Example: Creating a Full Name
Create a file called full_name.py and write this code:
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
When you run this program, the output is:
ada lovelace
Here is how it works:
- The f before the quotation marks tells Python you are creating an f-string.
- Inside the string, you use braces { } around a variable name to insert its value.
- Python replaces the variable with its value when printing the string.
These strings are called f-strings. The f means format, because Python is formatting the string with the variable values.
Example: Greeting with f-Strings
You can do much more with f-strings. Let’s make a greeting using the full name:
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
Here’s what happens:
- The variable full_name stores
"ada lovelace"
. - The code
full_name.title()
changes it to"Ada Lovelace"
. - The f-string combines everything into a friendly greeting.
The output is:
Hello, Ada Lovelace!
Example: Storing the Message in a Variable
You can also assign the whole message to a variable. This makes your code cleaner:
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
message = f"Hello, {full_name.title()}!"
print(message)
Now the output is the same:
Hello, Ada Lovelace!
But here, the message is stored in the variable message. This makes the print()
statement is simple and easy to read.
Adding Whitespace to Strings with Tabs or Newlines
In programming, whitespace means characters you cannot see, like spaces, tabs, or the end of a line. Even though you don’t see them directly, they are very important. They help you organize your output so it looks clean and easy to read.
Adding a Tab
You can insert a tab in a string by using \t
.
print("Python")
print("\tPython")
Output:
Python
Python
The second line is indented because the \t
adds a tab space.
Adding a Newline
You can move text to the next line with \n
.
print("Languages:\nPython\nC\nJavaScript")
Output:
Languages:
Python
C
JavaScript
Here, every \n
moves the output to a new line.
Using Tabs and Newlines Together
You can combine both. The string \n\t
means:
- First, go to a new line.
- Then, add a tab before starting the text.
Example:
print("Languages:\n\tPython\n\tC\n\tJavaScript")
Output:
Languages:
Python
C
JavaScript
Each language appears on a new line, and each one is indented with a tab.
Stripping Whitespace in Python
When you work with strings in Python, you must pay attention to whitespace.
Whitespace means extra spaces, tabs, or newlines that you might not notice at first.
For example, as humans, we see 'python'
and 'python '
as almost the same.
But for Python, they are two different strings. The second one has an extra space at the end, and Python counts that as important.
This can create problems. Imagine you are building a login system. A user types "Muneeb "
(with a space at the end) instead of "Muneeb"
. The system will see these as different usernames, and the login may fail.
So, controlling whitespace is very important. Luckily, Python gives us simple methods to handle this problem.
Removing Whitespace from Right Side
Python can check for whitespace on both sides of a string.
If you want to remove whitespace only from the right side, you use the rstrip()
method.
Example:
>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '
Let’s explain this step by step:
- The variable
favorite_language
has the value'python '
with an extra space at the end. - When you print the variable, you can see that extra space.
- When you use
.rstrip()
Python removes the extra space. But notice this is temporary. The original variable still has the space. - If you check the variable again, the space is still there.
So, rstrip()
only removes whitespace for that moment.
Removing Whitespace Permanently
If you want to remove whitespace permanently, you must save the new stripped value back into the variable.
Example:
>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python'
Now the variable favorite_language
no longer has the extra space.
This is very common in programming because we often update variable values based on user input or program output.
Removing Whitespace from the Left and Both Sides
Python also allows you to remove spaces from the left side using .lstrip()
, or from both sides using .strip()
.
Example:
>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'
Step by step:
- The original string
' python '
has spaces at both the beginning and end. .rstrip()
removes the space on the right side, but the left side still has a space..lstrip()
removes the space on the left side, but the right side still has a space..strip()
removes spaces from both sides, leaving only'python'
.
Removing Prefixes in Python
When working with strings, you often need to remove a prefix.
A prefix is the starting part of a string that you don’t want.
For example, consider a URL like this:
>>> nostarch_url = 'https://nostarch.com'
>>> nostarch_url.removeprefix('https://')
'nostarch.com'
Here, the URL starts with the prefix "https://"
.
By using the method .removeprefix('https://')
, Python removes just that part.
The result is 'nostarch.com'
.
This is useful because in many cases you only need the main part of the URL, not the prefix.
For example, when a user types a web address in the browser, they don’t always include https://
. The browser itself probably uses something similar to .removeprefix()
to handle it in the background.
How to Use .removeprefix()
- Start with the variable name.
- Add a dot (
.
). - Write
removeprefix()
. - Inside the parentheses, put the exact prefix you want to remove.
Example:
>>> simple_url = nostarch_url.removeprefix('https://')
>>> simple_url
'nostarch.com'
Here, we saved the result in a new variable simple_url
.
This way, we can keep the cleaned version of the URL without changing the original one.
Remember: removeprefix()
does not change the original string.
If you want the new version permanently, you must either reassign it to the same variable or store it in a new one.
Avoiding Syntax Errors with Strings
Another important topic when working with strings is syntax errors.
A syntax error happens when Python does not understand a piece of code.
This means the code is written in a way that Python does not recognize as valid.
One common mistake is using apostrophes incorrectly in strings.
Correct Way: Using Double Quotes
If your string contains an apostrophe, it is safer to put the string inside double quotes.
Example (apostrophe.py
):
message = "One of Python's strengths is its diverse community."
print(message)
Output:
One of Python's strengths is its diverse community.
This works perfectly. Python understands that the string starts and ends with double quotes, so the apostrophe inside does not confuse it.
Wrong Way: Using Single Quotes with Apostrophe
Now let’s see what happens if you try the same string with single quotes:
message = 'One of Python's strengths is its diverse community.'
print(message)
Python does not know where the string should end.
It sees the second single quote (after Python) and thinks the string has finished.
The rest of the text looks like random code, and Python cannot process it.
Result:
File "apostrophe.py", line 1
message = 'One of Python's strengths is its diverse community.'
^
SyntaxError: unterminated string literal (detected at line 1)
Notice the arrow pointing right after the single quote.
It shows where Python got confused and where the string seems to end.
Understanding Syntax Errors
Syntax errors are very common when you are learning Python.
They can be frustrating because they are the least specific type of error.
Sometimes Python just says: “Something is wrong with this line” without giving many details.
But don’t worry. Most syntax errors are simple mistakes like:
- Forgetting a closing quote.
- Using the wrong kind of quotes.
- Missing a parenthesis or colon.
As you practice, you will quickly learn to spot these errors and fix them.
Check out our Python Cheat Sheet for quick revision.
Other Chapters: