6) Variables and Types Lesson

Update Python Variables

4 min to complete · By Martin Breuss

The Python programming language is dynamically typed (or duck typed), which means that you can change the value and, more importantly, the data type of a variable after you define it.

Colorful illustration of a light bulb

Info: Conversely, in statically typed programming languages, you can't change the data type of a variable after assignment. There are advantages and disadvantages to both designs.

What is Duck Typing

Dynamic typing is also sometimes called duck typing. This term comes from the phrase "If it walks like a duck and it quacks like a duck then it must be a duck." Sounds logical---but maybe also slightly out of place in a programming context? Click the link on the quote above if you want to learn more.

Quacking duck by https://unsplash.com/@ross_sokolovski on Unsplash

Photo by by https://unsplash.com/@ross_sokolovski

Dynamic Typing Definition

In a nutshell, dynamic typing means that if you make a variable assignment, such as number = 2, at the beginning of your code, you can change number to a different value, e.g. 1889. You can even change it to point to a value of a different type, such as the string "Hei there buddy!".

Colorful illustration of a light bulb

Info: You will learn more about different data types in Python in an upcoming lesson.

How to Update a Python Variable

Updating the value of a variable is done by re-assigning the variable name to a different value, like so:

duck = 2
print(duck)  # 2
duck = 1889
print(duck)  # 1889
duck = "hei there buddy!"
print(duck)  # "hei there buddy!"

Throughout the lifetime of your short program shown above, the variable duck pointed to three different values! Note that the print() functions are just here to check up on the intermediate values of duck.

Duck Typing Advantages

Dynamic typing presents advantages for writing your code quicker. However, it also means that you need to take care since you don't want to accidentally change the value of a variable that you're using in your program. This could lead to all sorts of strange surprises!

In the next lesson, you'll learn about what these types of data are that you've read about here and there.

Summary: Update Python Variables

  • Variables in Python are dynamic, so their values can change
  • Dynamic typing is also referred to as duck typing
  • Re-assigning the variable name to a different value will update a Python variable