DEV Community

Benjamin Thorpe
Benjamin Thorpe

Posted on • Originally published at benjithorpe.hashnode.dev

Variables in Python

As a beginner, have you ever wondered what variables are or why we even need them??

Variables act as a container to store different types of values. They are one of the most important concepts in any programming language and are used to store information that can be used in our programs.

the example below shows how to create a variable:

name = "john"
Enter fullscreen mode Exit fullscreen mode

Every variable is connected to a value and we can access the value by calling the variable.
In the example above, "john"(the value) is assign to "name"(the variable).

Anytime we need to print "john" we just call "name" as in the example below:

print(name)

# --- output ---
>>> john
Enter fullscreen mode Exit fullscreen mode

you can change the value to be anything you want.

Need a number ??

age = 10
print(age)

# --- output ---
>>> 10
Enter fullscreen mode Exit fullscreen mode

Rules for creating variables:

When you create*(declare)* a variable, there are a few rules you must follow.
Breaking some of these rules will cause errors in your programs.

  • variable names can only contain letters, numbers, underscores
  • variable names can start with a letter or an underscore but not with a number
  • variable name cannot have spaces between them (use underscore eg: two_words)
  • never use keywords as variable name
  • variable names are case-sensitive (name, Name and NAME are three different variables).

here are some examples of bad variable declaration

2schools = "One and two"  # cannot start with a number

my name = "John"  # cannot have spaces (replace with "my_name")

pass = 10  # cannot use a keyword
Enter fullscreen mode Exit fullscreen mode

Summary

Variables may not seem interesting now, but they are very useful and you will use them frequently.

Bonus Resources

Top comments (0)