fbpx

How to declare and use a variable in Python

To declare and use a variable

1. Open the PyCharm Editor installed on your system. An introductory screen will show up on your system.

2. Click on “Create New Project” for creating your first project and starting to code in Python.

3. Select the location where you wish the project is to be created. You can change the name to something meaningful “NewProject”. Click on “Create”.

4. Next, go to the “File” menu and click on “New”. Click on the option “Python File”.

5. A pop-up window will appear where you can enter the filename.

6. Next, type the program.To assign a value to a variable, use the following command:
X=100
If we want to print the value of the variable, then
print(X)
Also, we can re-declare the variable in the same code.

7. The code would be as follows:

X=100                 #Variable declared initially
print(X)
x= ‘I love Python’
print(x)

8. Next, go to the “Run” menu and select “Run” for running the program. The shortcut for this is Alt+Shift+F10.

9. The output of the program will be displayed at the bottom of the screen.

Output:
This code will generate the

100
I love Python

Note:

In Python version 3, we use the print function as print(“x”) to print only the variable “x” whereas print(x) will print the value stored in x.

To delete a variable

1. Open the PyCharm Editor installed on your system. An introductory screen will show up on your system.

2. Click on “Create New Project” for creating your first project and starting to code in Python.

3. Select the location where you wish the project is to be created. You can change the name to something meaningful “NewProject”. Click on “Create”.

4. Next, go to the “File” menu and click on “New”. Click on the option “Python File”.

5. A pop-up window will appear where you can enter the filename.

6. Next, type the program. For deleting a variable in Python, we use the command del “variable name”.

7. The code would be as follows:

f=11;                   #Variable f declared and initialized
print(f)              #Value 11 is displayed as the output
del f                  #Variable f deleted
print(“f”)          #Will return an error since the given variable had already been deleted

8. Next, go to the “Run” menu and select “Run” for running the program. The shortcut for this is Alt+Shift+F10.

9. The output of the program will be displayed at the bottom of the screen.