Variables in Python
Let's find out about variables in Python:
Creating variables in python doesn't require any data type specification and can be used wherever needed and the variable is created.
Variable name conventions
Variables in python are commonly written in lowercase with an underscore separating multiword variable names[1], however it is upto you to follow any convention that is comfortable. CamelCase is the most commonly used in other languages, you can use fully upper case or any other convention. However it is best to stick to one convention throughout the project to have a consistent style. Because of my familiarity with java, I am going to choose CamelCase styling for naming variables and functions.
Variable cannot start with a number or a special character, however it can contain numbers in any other place of the variable name.
Try and copy the below code into a new python file in PyCharm and execute it.
exampleVariable = 5 # CamelCase convention which I am going to use.
print('exampleVariable=', exampleVariable)
# a variable can be quickly assigned as a result of an operation
exampleVariable1 = 5+2
print('exampleVariable1=', exampleVariable1)
# a variable can be assigned as a return value of a function
exampleVariable2 = print("Hello World!")
print('exampleVariable2=', exampleVariable2)
x, y = (1, 2) # feature called packing, assigning variables in bulk.
print('x=', x)
print('y=', y)
Packing is a feature in python where by you can assign multiple variables' values in a single line. It can be used in cases of co-ordinates as demonstrated by the above example.
You can create a variable as a return value of a function or a resultant value of an operation. This is similar to Java
As expected the output will be
exampleVariable= 5
exampleVariable1= 7
Hello World!
exampleVariable2= None
x= 1
y= 2
None
is the value of exampleVariable2
because the print() function does not return any value, it is equal to null in Java.
P.S: all the code used in this tutorial is available in github
Reference:
No comments:
Post a Comment