Python

Examples Of Variables In Python – Q&A

Data is stored in variables, which require memory space depending on the sort of value we assign to them. It’s easy to create variables in Python; just write the variable name on the left side of the equal sign (=) and the value on the right, as seen below. Python infers the type of the variable based on the value we are assigning, thus you are not required to state it directly.

num = 100      #num is of type int
str = "Chaitanya"      #str is of type string

Name of the variable: Identifiers

Id is another name for the variable name. While naming variables in Python, there are a few guidelines that you must adhere to.

1. Either a letter or an underscore (_) must always come before the variable name. For instance, the names _str, str, num, and _num are all acceptable names for variables.
2. A number cannot be the first character in the variable’s name. For instance, the variable name 9num is not acceptable.
3. Only alphanumeric letters and underscores (A to Z, a to z, 0-9, or _) may be used in the variable name; special characters such as %, $, and # are not permitted.
4. Python’s case-sensitivity for variable names means that num and NUM are two separate variables.

Example of Python Variable

num = 100
str = "BeginnersBook"
print(num)
print(str)

Output:
Python variables

Multiple Python assignments

In Python, many variables can be assigned in a single statement similar to this.

x = y = z = 99
print(x)
print(y)
print(z)

Output:

99
99
99

Another example of multiple assignment

a, b, c = 5, 6, 7
print(a)
print(b)
print(c)

Output:
Python multiple variables assignment in a single line

Variable plus and concatenation operation

x = 10
y = 20
print(x + y)

p = "Hello"
q = "World"
print(p + " " + q)

Output:
Python variable example

The following error will appear if you attempt to use the + operator with the variables x and p.

unsupported operand type(s) for +: 'int' and 'str'

Data Formats

A data type identifies the kind of data; for instance, “hello” is a string kind of data while “123” is an integer. Python divides its data types into two groups:
1. Immutable data types: It is impossible to modify a value.
2. Types of data that can change their values

Python’s immutable data types include:
1. Numbers
2. String
3. Tuple

Python’s mutable data types include:
1. List
2. Dictionaries
3. Sets

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button