DEV Community

Kajiru
Kajiru

Posted on

Getting Started with Python (Part 5): Working with Variables

Working with Variables in Python

In this chapter, the theme is variables.

By using variables, you can reuse specific values in your program.

What Is a Variable?

A variable is a mechanism that allows you to give a name to a value so that you can reuse it later.

In Python, you can think of a variable as attaching a label to a value.

You can choose variable names freely, but there are some naming rules:

  • A variable name cannot start with a number
  • It can contain letters, numbers, and underscores
  • Uppercase and lowercase letters are treated as different (msg and Msg are different)
  • Python reserved words (words with special meanings in Python) cannot be used

To assign a value to a variable, use the = operator.

variable_name = value
Enter fullscreen mode Exit fullscreen mode

Based on these rules, here is a sample program:

msg1 = "Hello"    # OK
msg2 = "Python"  # OK
2msg = "Python"  # NG (cannot start with a number)
if = "Python"    # NG (reserved word)
print(msg1)      # Hello
print(msg2)      # Python
Enter fullscreen mode Exit fullscreen mode

Using Variables

If a variable holds a number, you can use it in calculations.

num1 = 100
num2 = 10
num3 = 1

print(num1 + num2)  # 110
print(num2 + num3)  # 11
print(num1 - num2)  # 90
print(num1 * num2)  # 1000
print(num1 / num2)  # 10.0 (division results in a floating-point number)
Enter fullscreen mode Exit fullscreen mode

If a variable holds a string, you can concatenate it with other strings using +.

str1 = "Hop"
str2 = "Step"
str3 = "Jump"

print(str1 + str2 + str3)  # HopStepJump
Enter fullscreen mode Exit fullscreen mode

If a variable holds a number, convert it to a string using the str() function before concatenating.

famicom = "The release year of the Famicom: "
birth = 1983

print(famicom + str(birth))
# The release year of the Famicom: 1983
Enter fullscreen mode Exit fullscreen mode

Coming Up Next...

Thank you very much for reading!

The next chapter is titled “Working with Errors and Exceptions”.

Stay tuned!

Top comments (0)