Overview
Variables are containers for storing data values. Python has no command for declaring a variable, instead creating it when you first assign a value to it.
Example:
x = 8
y = "Johnny"
print(x)
print(y)
Note
Variables do not need to be declared with any particular type, and can even change type after they have been set.
Casting
If you want to specify the data type of a variable, this can be done with casting.
Casting in python is therefore done using constructor functions:
- int() – constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
- float() – constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
- str() – constructs a string from a wide variety of data types, including strings, integer literals and float literals
x = int(1) #x will be 1
y = int(3.6) #y will be 3
z = int("8") #z will be 8
x = float(1) #x will be 1.0
y = float(3.6) #y will be 3.6
z = float("8.5") #z will be 8.5
x = str("h1") #x will be 'h1'
y = str(3.6) #y will be '3.6'
z = str(8) #z will be '8'
Get the Type
You can get the data type of a variable with the type() function.
x = 8
y = "Johnny"
print(type(x))
print(type(y))
This will output:
<class 'int'>
<class 'str'>
Quotes and Case Sensitivity
String variables can be declared either by using single or double quotes.
x = "Johnny"
#is the same as
x = 'Johnny'
Variable names ARE case-sensitive
a = 8
A = "Johnny"
#A will NOT overwrite a
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
- Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
- Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), and unindexed (items cannot be referred to by index or key)
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.