Variables in Python are similar in many ways to variables in mathematics. Variable is a character(s) that acts as a placeholder and contains some value or information. A characteristic feature of variables is that, they vary! Their value is not fixed. In Python, variables are defined by assigning value to them using the =
symbol, called as the assignment operator. They can be used in place of the value they contain, i.e., they behave as if they are indifferent from their value.
x = 7 #The variable x is defined with the value of 7
y = 10 #The variable y is defined with the value of 10
print(x) #Gives the same output as print(7)
print(x + y) #Gives the same output as print(7 + 10)
x = 5 #Changes the value of x from 7 to 5
print(y - x) #Gives the same output as print(10 - 5)
Variables need not be single letter. It is important to note that although variable names may contain numbers, they cannot begin with one. Underscores are allowed and later versions of Python also allow you to use special unicode characters such as π
; yet, some special keywords are reserved (class, def, is, in, not, etc.) and trying to name a variable using them will result in an error. Variables in Python are case sensitive, meaning result
is different from Result
or REsulT
, which can be both useful and annoying.
Though rarely used, variables can also be deleted using del
. Another variable with the same can be created afterwards.
strength = 87 #Creates a variable strength with the value of 87
print(strength)
del strength #Deletes the variable strength
print(strength) #Gives an error, because strength is not defined anymore
Not only numbers, variables can be given any value. Try the following code:
name = Shetty777
print(name)
The above code should give an error! Because python doesn't know what Shetty777
is. However, enclosing the word in quotes (single or double) will make it a string and Python doesn't care what the contents of a string are (for most cases, there are some special characters which you'll get to know). Now try to run the above code, but with name = "Shetty777"
Values in Python must be ones that belong to a data type. type(data)
is used to get the data type of a value in Python. There are numerous data types in Python, but we are concerned about the basic built-in data types. They are:
Numeric types: int, float, complex
Sequence types: str, list, tuple
Mapping type: dict
Set types: set, frozenset
Boolean type: bool
None type: NoneType
As the name suggests, the int
type is the data type of integers, simple as that. E.g., 7, 100, 0, -46, 11 + 5
Decimal numbers upto a precision of 15 decimal digits are stored as float
. E.g., 3.7, 0.0628, 4 - 8.33, 2.997e8
The mathematics students among you might know that the root of -1 is i and numbers containing it are termed as complex numbers. The only difference is that the letter j
is used in its place. E.g., 5 + 2j, 0 - 4j, 0j
String type is just text, and it can contain unicode characters like π, α and λ. str
is defined by surrounding the characters by either single or double quotes, but not a combination of the two. E.g., '', "Hello", 'Python is awesome!', "It's so cool", "θ"
Unsurprisingly, a list
is a list of values. It is defined using square brackets and the elements are separated by commas. Lists can have elements of different types; they can have duplicates; they are mutable (modifiable). E.g., [0, 1, 2, 3], [7, 'Apple', 9j, ['a', 'b', 'c']]
A tuple
is basically a list, but it is immutable, meaning the values of elements cannot be changed. Elements cannot be added or removed either. They are defined by round brackets and the elements are separated by commas. Why would you want to use them? They are much more efficient in storing information. They can have duplicates; they can contain different types of elements. E.g., (7, 2025, 4, 899), ('Shashank', 16, 0.005)
A dict
in Python holds pairs of information in the format key:value
. The values can be accessed by the keys with the syntax dict[key]
. They can also contain different data types; they are mutable; but cannot contain duplicate keys. They are declared in curly brackets and the pairs are separated by commas. E.g., {0: 89, 1: 46, 2: 99, 3: 95}, {"name": "Shashank", "age": 16, "height": 1.56, 777: "blog site"}
A set
is basically a very efficient list. It cannot contain duplicates, if there are two elements with the same value, only one will be stored. They are unordered/not indexed; they can contain elements of different types; the elements are immutable, but you can add (set.add(element)
) or remove (set.remove(element)
) them. They are defined by curly brackets, with elements separated by commas.. E.g., {"Ruby", 3.1415, "Millie", (x, y, z)}, {10, 20, 10, 30, 40}
A frozenset
is almost indifferent from a regular set except that it is immutable as well. It is defined with the syntax frozenset({elements})
There are only two bool
values: True
and False
. Think of it as Yes or No. They will be useful in conditional statements. In fact, True is just a placeholder for 1 and False for 0; they are synonymous.
The NoneType
is a special type in Python which is used to represent the absence of a value. It is similar to null in other programming languages. It is the data type of None
and is not the same as 0. 0 is an integer whereas None is... literally nothing! This is used for debugging and safely handling empty data.
You can convert between data types using the target type as a function. There are limits of course, E.g., str(111)
is valid whereas int("Hi")
is not. Try different combinations for yourself.
score = 99 #Python detects the type of score as int
print(score, type(score))
score = "A+" #Python detects the type of score as str
print(score, type(score))
subject: str = "Science" #Type hinting the variable subject as str
marks: dict[str: int] = {"Physics": 100, "Chemistry": 95, "Biology": 98} #Type hinting the variable marks as dict with str keys and int values
a, b = 5, 10 #Same as a = 5; b = 10
print(a, b)
a, b = b, a #Swaps the values of a and b
print(a, b)
numbers: list[int] = [1, 2, 3, 4, 5] #Creates a list with the elements 1, 2, 3, 4 and 5
print(numbers[0])
text: str = "This is fun!"
print(text[2:7]) #Prints the elements from index 2 to 6 (7 is not included)
print("Apple\nBanana\nCherry") #\n is used to create a new line
print("Apple\tBanana\bCherry") #\t creates a tab and \b removes the previous character
print('ISRO\'s Chandrayaan-3\\Aditya-L1') #Using \ before characters that affect a string stops their effect, including another \.
name: str = "Shashank"
age: int = 16
print(f"Hello, my name is {name} and I am not {age + 10} years old.")
input()
. Here is an example:
a: str = input("Enter a number: ") #The input is always a string, so it must be converted to the desired type
b: str = input("Enter another number: ")
print("The sum is: ",int(a) + int(b))