When working on more complex pieces of code, you'll often find it useful to temporarily stash away values and to use them later. That's where variable assignment comes in handy. Let's look at an example:
WebGL support is required to run codetheblocks.com
If you ran the code above, you would have seen that the output of this script is 50.
As you can see, the syntax for assigning a value to a variable is destination = value. In the example above, n is the temporary place where we're storing the
value 50. We refer to n here as a "variable". Once assigned, we can use the
variable everywhere we would like to use the value to itself. The variable can
even be assigned to other variables. Let's see an example of that below:
WebGL support is required to run codetheblocks.com
Numbers aren't the only thing you can store in a variable. You can store pretty much anything.
WebGL support is required to run codetheblocks.com
Python does impose some restrictions on the names of variables:
Here are some examples of invalid variable names:
1numbervariables can not have spacesvariables_can't_have_quotesAll the above mentioned variables will lead to errors.
Here are some valid variable names:
nvariables_with_underscores_in_betweenthisAlsoWorksvariables_that_end_in_numbers_2_underscore_before_and_between__double_underscoresFor the purposes we've seen so far, underscore (_) separated variables are encouraged. This is also called "snake case" naming. In later lessons, you'll learn about other Python constructs where the convention is to use "camel case" variable naming, which uses upper-case letters to separate works like this: ThisIsCamesCase. But we're getting ahead of ourselves.
And last, but definitely not the least: variable names must be readable and
relevant. In the beginning, you'll be tempted to use variable names like x,
n etc. While these variable names have their place in software, as your
program gets more complex, you'll find it more useful to name your variables in
a way that reflects their purpose. We'll see examples of this in future lessons.
© 2024 Abhin Chhabra | Sitemap