Hello 👋🏼 and welcome to third blog of series The Pythonic Way. Now that you have written your first line of code in python. Its time to understand some basic elements of a python program i.e, Variables , Expressions and Comments.
A program is simply a sequence of definitions (which are evaluated) and commands (which are executed by the interpreter).
Objects and Type
Primitives are the fundamental objects that represent data in Python**.** All objects have a type that determines what kinds of things programs can do with them.
Objects can either be:
Scalar (cannot be subdivided into smaller parts)
Non-scalar (have an internal structure that can be accessed)
Scalar objects in Python include:
int - represent integers (e.g. 5 or 12)
float - represent real numbers (e.g. 3.14 or 7.001)
bool - represent either True or False values
NoneType - represent only one data type, None
You can use the type() procedure to find out the type of a value e.g :
Python 3.9.7 (default, Sep 16 2021, 08:50:36)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> type(3)
<class 'int'>
Here <class 'int'>
means that 3
belongs to a class of integers
You can also use the int() and float() procedures to cast, or convert, values into each other.
>>> float(3)
3.0
>>> int(3.9)
3
>>>
float(3) outputs 3.0
int(3.9) outputs 3
Expressions
Expressions are combinations of objects and operators
(e.g. <object> <operator> <object>
).
i+j - the sum of i and j (as a float if i or j is a float, otherwise an integer)
i-j - the difference between i and j (same as above)
i*j - the product of i and j (same as above)
i/j - the quotient of i and j (as a float)
i//j - the quotient of i and j as an integer (remainder excluded)
i%j - the remainder of the quotient of i and j
i**j - i to the power of j
Python follows the order of operations (everything is read from left to right in the order they appear), The acronym PEMDAS is a useful way to remember the rules:
() : parentheses
** powers
* or / : multiplication or division
+ or - : addition or subtraction
But when writing code it is better to use parenthesis to break long numeric expressions.
Variables
A Variable is a named place in the memory where a programmer can store data and later retrieve the data using a variable name.
As programmers, we decide the name of variables and can change the content of variables in a later statement.
Variables are useful because we can easily access and reuse their values (as opposed to recalculating values every time we need them). They also make code easier to read and work with.
Consider the code
pi = 3.14
radius=11
area = pi*(radius**2)
radius = 14
print(area)
The equals sign (=) assigns the name on the left to the value on the right (which is stored in the memory). This process of assignment is called binding (since we’re binding a name to a value). We can retrieve the value associated with the variable by invoking its name.
An assignment binds a name to a value, it first binds the names pi
and radius
to different objects of type int. It then binds the names area
to a third object of type int.
You can re-bind variable names using new assignment statements as we did in the above code radius=14. The previous value may still be stored in memory but lost the handle for it.
Note value for the area does not change until you tell the computer to do the calculation again.
Naming Python Variables
Must start with a letter or underscore _
Must consist of letters, numbers and underscores
Case sensitive
For example :
1r362tef = 3.14
1r362rfg = 11
1r362xyz = 1r362tef*(1r362rfg**2)
print(1r362xyz)
While the code will work perfectly but will make very much less sense when read by other people.
p = 3.14
b = 11
c = p*(b**2)
print(c)
This code is a little better when compared to the above. This can be read and understood by people that it is performing some mathematical operation.
pi = 3.14
radius = 11
area = pi * (radius ** 2)
print(area)
Using mnemonics is the best way to name a variable. It can be read and understood by other people that it is the calculating area of a circle using the value of pi and radius. But for Python, all the above 3 programs will work well and will show the same output.
More Expressions
The following are common comparison operators in Python:
i>j - greater than
i>=j - greater than or equal to
i<j - less than
i<=j - less than or equal to
i==j - equal to
i!=j - not equal to
All of the above comparison operators will return True
if true and False
if false.
The following are common logic operators on booleans in Python:
not a - will return the opposite of the true/false value that a is
a and b - will return True only if both a and b are true
a or b - will return True if either a or b are true
Another type of value is the string, a non-scalar value that consists of a sequence of characters such as letters, digits, or spaces enclosed in double or single quotes ( " "
or ' '
)
>>> name = 'aayush'
>>> type(name)
<class 'str'>
Here <class 'str'>
represents that value bonded in the variable name
is belongs to the class of strings
Since strings are non-scalar, they can work with several different operations:
>>> 'hello' + 'aayush'
'helloaayush'
+
operator concatenates two strings
>>> 3 * 'aayush'
'aayushaayushaayush'
*
successive concatenation of aayush
three times
We will read about strings operation and manipulation later :-)
User Input
Sometimes we would like to take the value for a variable from the user via their keyboard. Python provides a built-in function called input
that gets input from the keyboard. When this function is called, the program stops and waits for the user to type something. When the user presses Return
or Enter
, the program resumes and input
returns what the user typed as a string.
>>> inp = input()
The Pythonic Way
>>> print(inp)
The Pythonic Way
Before getting input from the user, it is a good idea to print a prompt telling the user what to input. You can pass a string to input
to be displayed to the user before pausing for input.
>>> name = input('What is your name?\n')
What is your name?
Aayush
>>> print(name)
Aayush
The sequence \n
at the end of the prompt represents a new-line, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.
If you expect the user to type an integer, you can try to convert the return value to int
using the int()
function:
>>> radius = int(input("enter value of radius\n"))
enter value of radius
11
>>> print(radius**2)
121
Comments
As programs get bigger and more complicated, they get more difficult to read and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and in Python, they start with the #
symbol:
# computer the area of circle
area = pi * (radius ** 2)
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
area = pi * (radius ** 2) # computer the area of circle
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.
This comment is redundant with the code and useless:
radius = 5 # assign 5 to radius
This comment contains useful information that is not in the code:
radius = 5 # radius in meters.
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a trade-off.
We will read all about condtional statements in next blog, so stay tuned 😄
Liked this article. Follow me on twitter 🐦
References
(Dr. Charles R. Severance, Python for Everybody : Exploring Data Using Python 3 , Chapter 2: Variables)