Variable Names

When it comes to writing names for variables, there are certain conditions that are suitable. This means that only certain characters are allowed for the name of variables, these characters being letters, numbers, and underscores. In addition, variable names can not start with a number and can not have spaces between each word otherwise the resulting code will end in an error.

[Console]

>>>Hello_World = 7

>>>print(Hello_world)


 

>>>123spam = 4

>>>print(123spam)


 

>>>Hello World = 3

>>>print(Hello World)

=====

[Interpreter]

7

 


Error

 


Error

 

NB – this is very important! Python is a case sensitive language therefore a variable named Hello_world will be different to hello_world.

 

If there is a code with a variable without an assigned value it causes an error to occur. However this can be repaired by using the del statement to remove the variable. In doing so, the variable is deleted. If you were to try and reference the variable after the del statement then an error would occur as that variable has been deleted. Since the variable has been deleted, the variable can be later reassigned to another value later on. An example would be similar to this (excuse the formatting here):

>>>eggs = “Hello World”

>>>eggs

Hello World

>>>Spam

NameError: name “Spam” is not defined

>>>del eggs

>>>eggs

NameError: name “eggs” is not defined

Another, more complicated, example is demonstrated below:

* the value of the variable can also be assigned via user input

>>> eggs = input(“Enter a number:”)                             Enter a number = 4

>>print(“eggs”)

4

 

[Console]

>>> spam = 1

>>> eggs = 2

>>> del spam

>>> eggs = 3

>>> spam = 4

>>> print(spam * eggs)

=====

[Interpreter]

12

*the value of the new variable of eggs replaces the older value and since the first value of spam is deleted, a new value can be reassigned.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s