Variables are used to store data (like string, integer or complex data) in memory. You can change or access this memory location in a program by its reference (variable name). In Python, a variable is created when you assign a value to it.
# Variable Creation
pi = 3.14
number = 5
Name = "John"
Python is a dynamically-typed language. In dynamically-typed languages (like Python, PHP, JavaScript), variable type isn’t known until the code is executed at runtime. Thus, you can assign different data types to a variable.
In statically-typed languages (like Java, C++) you need to declare the data type of a variable before using it and the type of each variable is known at compile time.
foo = 5 # foo is an integer type variable
foo = "John" # now, foo is a string type variable
# you can assign different data types
# to the same variable, because
# Python is a dynamically-typed language.
Concatenating with + Operator
You can use + operator to concatenate two string variables. However you cannot concatenate a string and an integer value, it will raise a TypeError
. Since Python does not convert an integer to string implicitly, you need to use the built-in str()
function to convert an integer to string value.
TypeError: can only concatenate str (not “int”) to str
hello = "Hello "
number = 5
print(hello + number)
Correct
hello = "Hello "
number = 5
print(hello + str(number))
Variable Naming
You need to follow a few rules to name your variable:
- A variable name should start with a letter or an underscore (_) character.
- A variable name can contain any alphabetic (A-Z a-z), numeric (0-9) or underscore (_) character but the first character cannot be numeric.
- Variable names are case sensitive (MyVar, myvar, myVar all refer to different variable).
Valid variable names:
- myVar
- _myVar
- myVar2
Invalid variable names:
- 2myVar (variable names cannot begin with a number)
- myVar@new (variable names can only contain alpha-numeric or underscore characters)
- yield (yield is a reserved word in Python. If you use reserved words as variable names, Python compiler will give an error)