Skip to content

Commit bfa17a3

Browse files
Add Python docs on using literal values instead of variables.
1 parent 608174b commit bfa17a3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/python/python-language.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2089,6 +2089,31 @@ def update_score():
20892089
score = score + 1 # 1
20902090
```
20912091

2092+
### Using literals instead of variables
2093+
2094+
You don't always need a variable to hold a value. If you're only going to use a value in a single place, it may make more sense to use the bare value (called a _literal_ value) instead.
2095+
2096+
For example, in this program, a random item is chosen from the `favorite_foods` `list`:
2097+
2098+
```python
2099+
from random import choice
2100+
2101+
favorite_foods = ["taco", "pizza", "fries"]
2102+
random_food = choice(favorite_foods)
2103+
```
2104+
2105+
If we're not going to use the `favorite_foods` `list` anywhere else in our program, we could write the same logic like this:
2106+
2107+
```python
2108+
from random import choice
2109+
2110+
random_food = choice(["taco", "pizza", "fries"])
2111+
```
2112+
2113+
!!! note
2114+
2115+
This example exists to show you that you **can** use a value in place of a variable. It is almost always more appropriate to give a good variable name to a value instead of using the literal value.
2116+
20922117
_Further Reading_
20932118

20942119
- [Real Python - Variables in Python](https://realpython.com/python-variables/)

0 commit comments

Comments
 (0)