How to assign values to variables in Python

PythonServer Side ProgrammingProgramming

Variable assignment is a very basic requirement in any computer programming language. In python there are multiple ways we can declare a variable and assign value to it. Below we see each of them.

Direct Initialisation

In this method, we directly declare the variable and assign a value using the = sign. If the variable is declare multiple times, then the last declaration’s value will be used by the program.

Example

x = 5
x = 9
print(a)

Running the above code gives us the following result:

Output

9

Using if-else

We can initialize value of a variable using some conditions. The evaluation of the result of the condition will become the value of the variable.

Example

 Live Demo

x = 12
y = 13 if x > 8 else 0
# printing value of a
print("Value of z is: " + str(y))

Running the above code gives us the following result:

Output

Value of z is: 13
raja
Published on 20-Dec-2019 15:32:35
Advertisements