J
last year
Joaocountry asked

Why is it better to convert a variable to a string instead of converting the value directly? For example, what's the difference between these two approaches: number = 5.5 number_str = str(5.5) vs. number = 5.5 number_str = str(number)

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Good question — both approaches will give you the same result: the string "5.5". But there’s a subtle difference in flexibility.

In the first version:

number_str = str(5.5)

You're hardcoding the value 5.5. This works fine, but it's less reusable.

In the second version:

number = 5.5  
number_str = str(number)

You're converting the value stored in the variable number to a string. This makes your code more flexible — if the value of number changes later, you don’t need to update multiple places in your code.

So while both are technically correct, using the variable is generally the better practice.

Python
This question was asked as part of the Getting started with Python course.