Python – Variable

After reading this Python Variable topic, you will understand how to create and manipulate Variable, and you will understand how to assign and display variable data in Python.

In python, an assignment statement automatically generates variable.

Assign value to a Variable

An assignment statement used for assigning a value to a variable. The assignment statement generally having the symbol = which is known as the assignment operator.

Example:

Program (1): To demonstrate how to assign a value to a variable in Python.

x=10
print(x)

Output (1)

10

Explanation: for Program(1) and Output(1)

  • x is variable.
  • 10 is the value assigned to variable x.
  • = is the assignment operator.
  • Print statement to display variable x value.

Assign string to a Variable

An assignment statement used for assigning string to a variable.

Example:

Program (1): To demonstrate how to assign string to a variable in Python.

x="Hello"
print(x)

Output (1)

Hello

Explanation: for Program(1) and Output(1)

  • x is variable.
  • Hello is the string assign to variable x.
  • string generally written in the pair of double inverted commas (i.e. ” “)
  • = is the assignment operator.

Display Variable Data

The print statement used to print variable data.

Example:

Program (1): To demonstrate how to display variable data in Python.

x=5
print("The x is ",x)

Output (1)

The x is 5

Explanation: for Program(1) and Output(1)

  • x is variable.
  • = is the assignment operator.
  • Print statement to display variable x value.

Assign multiple Variables

We can assign values to multiple variable in single statement.

Example:

Program (1): To demonstrate how to assign a value to multiple variables in Python.

x, y, z = 100, -45, 0
print('x =', x, ' y =', y, ' z =', z)

Output (1)

x = 100 y = -45 z = 0

Explanation: for Program(1) and Output(1)

  • x, y, and z are variables.
  • 100, -45 and 0 are the values assign to variables x, y, and z respectively.
  • = is the assignment operator.
  • Print statement to display variables x, y and z values.

Python – Rules for defining Variable Name

  1. An alphabet or underscore used in the starting letter of the variable name.
  2. A variable name cannot be keywords or standard function name.
  3. A variable name length is compiler dependent.
  4. Only underscore in special characters is allowed.
  5. A variable name is case sensitive i.e. uppercase letters and lower case letters are different.

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

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