In the previous post, we saw what is Python, how to install and wrote a basic Hello World program. This post aims to explain some key concepts in Python including variables, operators and data types.
Keywords
Like any other programming language, Python also has certain keywords. Keywords are reserved words in a programming language which have a special meaning and cannot be used for user defined purposes such as naming variables, functions etc. Some of the keywords in Python include if
, else
, in
, for
, True
and so on…
We will learn some of the keywords and their uses in this post and future posts.
Data Types
Data types denote the kind of data in a programming language. Programming languages evaluate and process the data based on the data types. Data types can be broadly classified into 2 categories viz., Primary/Built-in or Composite/User-defined data types. We will cover some of the built-in Python data types here.
Python built-in data types can be classified into the following categories i.e., numerics, text, sequences, mappings, classes, instances and exceptions.
Numeric data types
Python has 3 numeric data types which are given as under:
Data Type | Data Type Name | Description |
---|---|---|
int | Integer | Integer data type with unlimited precision. |
float | Float | Decimal data type with precision limited to what is supported by the operating system on which the program is executed |
complex | Complex Numbers | Complex numbers with a real part (<variable_name>.real ) and imaginary part (<variable_name>.imag ) |
Apart from the above, a boolean type (bool
) also exists in Python which is a sub-type of int
and has True
and False
as the only possible values. It is mainly used for logical operations.
Numeric data types support a wide range of operations in Python, which is covered in a later section in this post.
Text data type
Text data type is a part of the various Sequence data types. In Python, the String (str
) data type is used for text-based operations and represents a sequence of characters. Strings can be enclosed within single quotes (''
), double quotes (""
), three single quotes (''' '''
) or three double quotes (""" """
).
When strings are enclosed within three single/double quotes, they can span multiple lines inclusive of any whitespace on each of the lines.
List data type
List data type (list
) is another data type within the Sequence data types. It represents an array of data members wherein each data member can be of any type. In Python, lists are represented by square brackets ([]
) and members within are separated by commas (e.g. [1,'1',2.3]
).
Length of sequences
Length of any sequence data type can be found out using the len()
function. Thus, we can use the same len()
function to find out length of Strings as well as Lists.
Operators
Operators are used to carry out some calculations or operations during the execution of a program. Python has various operators and some of them are covered as under:
Assignment operator
The =
operator is the assignment operator in Python and is used to assign values to variables in Python. (Variables are covered in a later section of this post)
Numeric Operators
Numeric operators are used to carry operations on numeric data types. The list of numeric operators is as under:
Operator Symbol | Description |
---|---|
+ | Addition of 2 numbers |
- | Subtraction of 2 numbers |
* | Multiplication of 2 numbers |
/ | Division of 2 numbers |
// | Floor division of 2 numbers (returns only the integer part of the quotient) |
% | Modulo (returns the remainder) |
** | Exponentiation (raises the 1st number to the 2nd number) |
-x | Variable (say, x) negated |
Sequence Operators
Similarly, sequence operators are used to carry operations on sequence data types. The list of sequence operators is as under:
Operator | Description |
---|---|
in (e.g. x in y ) | Returns True if an item of the former variable (say, x) is present in the latter variable (say, y) and False if otherwise. |
not in | Returns True if an item of the former variable (say, x) is not present in the latter variable (say, y) and False if otherwise. |
+ | Concatenates / joins two sequences. (e.g. "AB"+"CD" would result in "ABCD" ) |
* | Repeats the given sequence for n times. (one of the operands must be an Integer) |
Logical Operators
Logical operators are the operators used to perform logic-based operations in Python. Logical operators always evaluate to either True
or False
. The list of these operators is as under:
Operator | Description |
---|---|
== | Checks whether two values or variables are equal or not |
!= | Checks for inequality of 2 values or variables |
> | Checks whether a value is strictly greater than the other |
>= | Checks whether a value is greater than or equal to the other |
< | Checks whether a value is strictly smaller than the other |
<= | Checks whether a value is smaller than or equal to the other |
and | Boolean AND (Checks whether two conditional expressions evaluate to True ) |
or | Boolean OR (Checks whether any of the two conditional expressions evaluate to True ) |
not | Boolean NOT (Reverses the evaluated value of a conditional expression) |
Operator Precedence
While evaluating any expression, Python follows an order in which it evaluates the expression. Python evaluates any expression from left to right and gives the following precedence to the operators (highest to lowest):
- Brackets - Parenthesis (
()
), Square brackets ([]
) and Curly brackets ({}
) - Expressions within brackets are evaluated first. - Exponentiation -
**
- Positive and Negative -
+
or-
to any variable - Multiplication and division -
*
,/
,//
,%
- Addition and subtraction -
+
,-
- Comparisons -
in
,not in
,is
,is not
,<
,<=
,>
,>=
,==
,!=
- Boolean NOT -
not
- Boolean AND -
and
Expressions
An expression in Python is composed of two or more operands and one or more operators.
Eg. 2+4*8
is an expression.
Variables
Variable is an user-defined named location which stores some value as a result of assignment by the user or as a result of some calculation at runtime. Generally, every variable stores data of a particular data type. However, Python follows a different approach with variables. The type of any variable in Python is not fixed while writing the program and is determined dynamically at run-time which means a variable can hold different data types during the execution of a program.
Declaring a variable
There is no keyword for declaring variables in Python. You just have to declare a variable on a fresh line by giving it a name of your choice (Make sure to follow the below rules).
Variable naming rules
Certain rules exist for naming variables in Python which are as under:
- Variable names should not be keywords (such as
if
,is
,in
,for
etc). - Variable names must start with an alphabet or an underscore (
_
). - Variable names can contain only alphanumeric characters and underscore (
_
). - Python variable names are case-sensitive (i.e., variable AB is different from ab, Ab and aB).
Assigning a value to a variable
Variables are assigned values using the assignment operator.
a = "Hello"
Determining variable type
Since variable types can change during the execution of a program, it is important for a developer to know the type of the variable at any given point. This can be accomplished using the type()
function.
a = 24
print(type (a))
# Output: <class 'int'>
Functions
A function is a named reusable block of code. In Python, functions are defined using the def
keyword.
Some examples of built-in Python functions are print()
, input()
, type()
, abs()
etc.
User-defined functions will be covered in detail in a future post.
Comments
Comments are the statements in a program which are not executed or compiled when the program is run. These are important from a software developer’s point of view as it helps to note down the usage of the code or important points in the code itself. Various types of comments are covered as under:
Single-line comments
Single-line comments are comments which are limited to a line itself. The hashtag (#
) symbol is used to start a single line comment.
# This is a single-line comment.
Multi-line comments
Multi-line comments can be used by using multi-line strings ( covered earlier).
"""
This is
a multi-line comment
"""
Example Program
Let’s see some of the concepts covered above in a Python program.
Program:
# A single line comment.
''' This program is all about the above concepts:
- Variables
- Data Types
- Operators
'''
a = "Hello World!"
b = 22
c = 2.5
d = 45
print (type(a)) #Type of a: String
print (type(b)) # Type of b: Integer
b = "Hello" #Changed type in program.
print (type(b)) # New data type.
print (b in a) # True as Hello is a part of a
# Basic maths
print ("Operators: ")
print(c+d)
print(d-c)
print(d*c)
print(d/c)
print(d**c)
print(d%c)
# Sequence operators
print ("Sequence: ")
print (a+b)
print (b*2)
# Logical
print ("Logical: ")
print (c!=d)
print (c<d)
Your output should look something like this:
Summary
To summarize, this post covered certain key concepts of Python which are important and serve as a good point to start learning Python. Thank you for reading through and hope you learnt something from this post.