Why would I print a variable instead of just printing the string?

Question

Why would I print a variable instead of just printing the string?

Answer

Often when you write a program you’ll be displaying things that change based on user input. For example, if you want to greet a user with ”Hello, username, good to see you!”, you can’t possibly know everyone’s username when writing your program. So you’d take their username as input and store it in a variable, and then you can print it later as a variable, rather than a hard-coded string!
This concept of avoiding hard-coding is generally a good practice because it allows for code that works more broadly, and should be something you actively look for when trying to improve your code.

32 Likes

That’s a good answer, plus I would add that variables can be short and descriptive. You might have a string that is very long and would take a long time to type (with the possibility of errors), but once stored in a short variable you have access to that whole long string just by re-using that short variable you once declared.

16 Likes