Using Variables in Python
- Variables in Python are very flexible.
- You create them when you want them.
- If Python can, it will create them for you.
Making a variable
To create a variable in Python, just think of a name and assign it a value (with the equals sign)
myStupidVariableName = 0
There aren't many rules about what your variable should be called. There are a few though and you should know:
- a variable name can't start with a number
- a variable name can't have spaces in it and shouldn't have strange characters like !$%£$
- CASE MATTERS. In other words MYStupidVariable and mySTUPIDvariable are DIFFERENT variables.
- it shouldn't be a keyword. You can find a list of these by typing 'help' and then 'keywords' at the python prompt. At the moment it looks like this:
so don't use variable names that look like these words.
The main rule is - be consistent.
The main rule is - be consistent.
The one thing that can go wrong
Python tries to help you out. If it sees what looks like a variable it will usually create one for you.
However if you try and USE a variable before you've created it, or before Python has had the opportunity to create it for you, the program will crash. Like this:
However if you try and USE a variable before you've created it, or before Python has had the opportunity to create it for you, the program will crash. Like this:
This is the kind of thing that can happen if you're careless about Capitalisation. In this case myStupidVariable (with capital S and V) was never assigned before it was used in the print statement. Python didn't know what to do, so it crashed.
The awesome invisible automatic types
Python works behind the scenes to make sure that your variable is the right type (Text or numbers) without bothering you. Usually it gets it right. Sometimes you need to force a variable to be a particular type. There are two keywords that can do this:
myVariable = int(myVariable)
Forces myVariable to be an integer (whole number) type.
myVariable = str(myVariable)
Forces myVariable to be a string (Text) type.
You can find out what type a variable is by using the keyword 'type'
Like this:
You can find out what type a variable is by using the keyword 'type'
Like this: