2.1 Variable Names

Python variable names can contain any alphabetic characters (A-Z and a-z), digits (0-9), and the underscore character "_". There are some caveats and restrictions:

  1. Uppercase and lowercase letters are distinct. Therefore, "Number" and "number" are two different variables.
  2. A digit cannot start a variable name. Therefore, "student1" is a valid variable, while "1student" is not.
  3. Built-in keywords and function names shouldn't be used as a variable name. For example, "print" is obviously a Python keyword, therefore you shouldn't be using it as your variable name.

That being said if you use single letters as variable names most Python linting will complain. Best practice is to use a short descriptive name to make the code clear.

2.2 Declare a variable and initialize it

f = 0;
 
print f

note the semi-colon at the end of a statement.

2.3 Re-declare a variable

f = 0;
f = "abc"
 
print f

no problem with that

2.4 Combine like type

Pyhon is a strongly typed language

this won't work.

print "string type " + 123

this is OK, you can cast a variable as a type.

print "string type " + str(123)

note the use of python's built in string conversion function str() to cast 123 as a string

2.5 Global vs. local variables in functions

# Declare a variable and initialize it
f = 0;
print f
 
# Global vs Local Variables
def someFunction():
# global f
  f = "def"
  print f
 
someFunction()
 
print f 
 
del f
 
print f

If you want to access the variable f outside the function you need to uncomment global f making the variable a global variable.

In addition the last print f statement throws an error since, once a variable is deleted it is no longer defined… that seems obvious...