# How to assign values to variables in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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
Updated on 20-Dec-2019 11:07:16