Lesson 4

Exploring Variables and Strings in Python

What You'll Learn

Ready to explore combining text with variables in Python using f-strings? This powerful feature makes it effortless to create dynamic and readable strings by embedding variables directly within them.

Code Example

For a trip planning scenario, consider these variables:

Python
1# Travel variables 2destination = "Paris" 3number_of_days = 5 4trip_cost = 1200.50 # Notice how we can store numbers in variables that are not integers!

Using f-strings enables you to neatly include variable values in your text output:

Python
1# Using f-strings for travel details 2print(f"I am planning a trip to {destination}.") 3print(f"The trip will be for {number_of_days} days.") 4print(f"The estimated cost of the trip is ${trip_cost}.")

output:

Plain text
1I am planning a trip to Paris. 2The trip will be for 5 days. 3The estimated cost of the trip is $1200.5.

f-strings allow for inline variable insertion, which means you can directly insert the value of a variable into a string by prefacing the string with f and enclosing variable names in curly braces {}.

Why It Matters

F-strings offer a concise and readable way to incorporate variables into strings, enhancing code clarity. They're especially useful for outputting data in a more engaging and informative manner. Through practice, you'll get comfortable with this skill, which is crucial for effective Python programming.

Let's dive into the practice exercises!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.