robertbearclaw.com

Master Python Basics: Understanding Variables and Strings

Written on

Chapter 1: Introduction to Python Programming

In our journey to become proficient Python programmers, we’ve made a simple yet iconic modification of the universally recognized code: "Hello, World!".

If you're traveling, avoid expensive roaming fees with Saily eSIM, powered by NordVPN and NordPass.

This article is part of the "Start Coding with Python" series (check out the complete list).

To begin, you’ll want to create a file named with the .py extension, for example, greeting.py, containing the following code:

print("Hello everyone on Medium!")

When you execute this in your terminal, it will output the intended greeting:

$ python3 greeting.py

Hello everyone on Medium!

By saving your file with a .py extension, the Python interpreter recognizes the word print, which is followed by parentheses, allowing it to display the text inside. It identifies print() as a function and understands that "Hello everyone on Medium!" is simply a string, which is visually distinct in color due to syntax highlighting.

Variables

Let’s adjust the greeting.py file:

var = "Hello everyone on Medium!"

print(var)

Running this will produce:

$ python3 greeting.py

Hello everyone on Medium!

Here, the value "Hello everyone on Medium!" is linked to the variable var, which the print function will display. If we enhance our greeting.py file further:

var = "Hello everyone on Medium!"

print(var)

var = "Hello everyone on Substack!"

print(var)

Executing this code will yield two lines of output:

$ python3 greeting.py

Hello everyone on Medium!

Hello everyone on Substack!

As you might expect, the variable var always adopts the latest assigned value. Variables are invaluable as they can be modified at any point in the code. Keep in mind that variable names can only include letters, numbers, and underscores, and cannot start with a digit, such as 1_var.

Strings

In our previous code, we enclosed a standard sentence in quotes, like "Hello everyone on Medium!". This sentence is classified as a string, which is essentially a collection of characters. You can utilize either single or double quotes:

string1 = 'I said, "Be careful, his bowtie is really a camera"'

print(string1)

string2 = "Who is 'Kathy' in Simon & Garfunkel's song America?"

print(string2)

If you execute this code, naming it america.py, the output will look like this. Pay attention to how the quotes and apostrophes are structured:

$ python3 america.py

I said, "Be careful, his bowtie is really a camera"

Who is 'Kathy' in Simon & Garfunkel's song America?

In Python, altering the case of strings is straightforward. Consider this example in a file named name.py:

name = "jim morrison"

print(name.title())

Running this code will yield:

$ python3 name.py

Jim Morrison

What occurred here? The method title() follows the variable name, indicating an action on the data. Thus, title() modifies the variable name. Remember that the dot (.) signifies the method applied to the variable. You'll quickly become accustomed to this syntax with additional examples. If a method requires further information, it will be included within the parentheses. In this case, title() does not need any extra details, hence the empty parentheses.

To explore case manipulation further, let’s modify our file as follows:

name = "Jim Morrison"

print(name.upper())

print(name.lower())

The output upon execution will be:

$ python3 name.py

JIM MORRISON

jim morrison

Variables within Strings

Now, let's write code that incorporates variables:

first_name = "Jim"

last_name = "Morrison"

full_name = f"{first_name} {last_name}"

print(full_name)

Here, we define two variables, first_name and last_name, and aim to output the full name using these variables. Note the syntax f"{variable1} {variable2}", which utilizes f-strings (where 'f' stands for format). This allows Python to substitute the variable names within the braces with their corresponding values.

When you execute this code, the output will display the full name:

$ python3 name.py

Jim Morrison

By using f-strings, we can enhance code flexibility. Consider this revised version:

first_name = "jim"

last_name = "morrison"

full_name = f"{first_name} {last_name}"

print(f"Hello Medium, I am {full_name.title()}!")

Can you predict the output? It will indeed reflect the title case changes in the variables, yielding:

$ python3 name.py

Hello Medium, I am Jim Morrison!

If we alter the code slightly to:

first_name = "jim"

last_name = "morrison"

full_name = f"{first_name} {last_name}"

message = f"Hello Medium, I am {full_name.title()}!"

print(message)

And run it, the output remains consistent:

$ python3 name.py

Hello Medium, I am Jim Morrison!

Explore the basics of Python programming with this tutorial for absolute beginners, focusing on variables and strings.

This full course tutorial is designed for beginners looking to dive deep into Python programming fundamentals.

References

[1] Python Crash Course 3rd ed., Eric Matthes, (shop online & buy the book).

[2] Python Programming and Computer Programming

Support my work at no extra cost, and enjoy savings while shopping online: visit My Affiliate Storefront, featuring 50% Off Promo Codes. Secure your online presence with top-tier services from NordVPN (69% Off limited time deal) and NordPass Premium (50% Off limited time offer), both come with a 30-day money-back guarantee! Get Deals Now!

Photo by Christopher Gower on Unsplash

This post contains affiliate links. Clicking on them and making a purchase may earn me a commission at no extra cost to you. Please consider supporting me with a small contribution of $1 (No sign-ups required! Just Tap & Tip).

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Innovative Space Debris Removal: A Look at ClearSpace's Mission

ClearSpace's mission to tackle space debris is a groundbreaking initiative that could reshape our approach to orbital waste management.

# Overcoming Phone Addiction: A Journey to Digital Freedom

Discover how to combat phone addiction using insights from

Harnessing AI with Snowflake's Cortex LLM Functions

Discover Snowflake's new Cortex LLM functions for AI integration in data warehousing, enhancing productivity and data management.