Python 1 Unit
Python 1 Unit
In Python, an identifier is the name assigned to a variable, function, class, or other object. It is
used to refer to the object in the program and is a way to give the object a human-readable
name. In Python, an identifier must follow certain rules to be valid.
The identifier cannot begin with a number or any other special character.
The remaining characters in the identifier can be letters, numbers, or underscores. This means
that an identifier can contain letters, numbers, and underscores but cannot contain any other
special characters.
The second rule for an identifier in Python is that it must be unique within the scope in which it is
used. This means you cannot have two variables with the same name in the same scope or two
functions with the same name in the same module. Attempting to do so will result in a Name
Error.
The third rule for an identifier in Python is that it cannot be a reserved word. Python has a set of
reserved words that cannot be used as identifiers. These include keywords like if, else, for, while,
and so on. A Syntax Error will be returned if you attempt to use a reserved term as an identifier.
Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.
example:
a = 50
Expressions in Python
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric
values, operators, and sometimes parenthesis. The result of this type of expression is
also a numeric value. The operators used in these expressions are arithmetic operators
like addition, subtraction, etc. Here are some arithmetic operators in Python:
Synta
Operators Functioning
x
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
Example:
Python3
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating
point numbers as result after all computations and type conversions.
Example:
Python3
# Floating Expressions
a = 13
b =5
c =a /b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are
written on both sides of relational operator (> , < , >= , <=). Those arithmetic
expressions are evaluated first, and then compared as per relational operator and
produce a boolean output in the end. These expressions are also called Boolean
expressions.
Example:
Python3
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: These are kinds of expressions that result in
either True or False. It basically specifies one or more conditions. For example, (10 ==
9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False.
Studying logical expressions, we also come across some logical operators which can be
seen in logical expressions most often. Here are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
Example:
Let’s have a look at an exemplar code :
Python3
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
Python3
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a
single expression, and that will be termed as combinational expressions.
Example:
Python3
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
But when we combine different types of expressions or use multiple operators in a
single expression, operator precedence comes into play.
It’s a quite simple process to get the result of an expression if there is only one operator
in an expression. But if there is more than one operator in an expression, it may give
different results on basis of the order of operators executed. To sort out these
confusions, the operator precedence is defined. Operator Precedence simply defines the
priority of operators that which operator is to be executed first. Here we see the
operator precedence in Python, where the operator higher in the list has more
precedence or priority:
Precedenc
e Name Operator
1 Parenthesis ()[]{}
2 Exponentiation **
8 Bitwise XOR ^
9 Bitwise OR |
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
So, if we have more than one operator in an expression, it is evaluated as per operator
precedence. For example, if we have the expression “10 + 3 * 4”. Going without
precedence it could have given two different outputs 22 or 52.
# Multi-operator expression
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python
expression.
Python Operators
The operator is a symbol that performs a certain operation between two operands, according to
one definition. In a particular programming language, operators serve as the foundation upon
which logic is constructed in a programme. The different operators that Python offers are listed
here.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operations between two operands are carried out using arithmetic operators. It
includes the exponent (**) operator as well as the + (addition), - (subtraction), * (multiplication), /
(divide), % (reminder), and // (floor division) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20
- It is used to subtract the second operand from the first operand. If the
(Subtraction) first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplicatio = 4 => a * b = 80
n)
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Comparison operator
Comparison operators compare the values of the two operands and return a true or false Boolean
value in accordance. The following table lists the comparison operators.
Play Video
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second
operand.
>= The condition is met if the first operand is greater than or equal to the second
operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Assignment Operators
The right expression's value is assigned to the left operand using the assignment operators. The
following table provides a description of the assignment operators.
Operator Description
+= By multiplying the value of the right operand by the value of the left operand,
the left operand receives a changed value. For example, if a = 10, b = 20 =>
a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a =
10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10
=> a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. Consider the case
below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ The operand's bits are calculated as their negations, so if one bit is 0, the
(negation) next bit will be 1, and vice versa.
<< (left The number of bits in the right operand is multiplied by the leftward shift of
shift) the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Logical Operators
The assessment of expressions to make decisions typically makes use of the logical operators.
The following logical operators are supported by Python.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a
and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it returns
false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be
true (list, tuple, or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Identity Operators
Operator Description
is not If the references on both sides do not point at the same object, it is determined
to be true.
Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which
operator needs to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater than,
greater then equal to).
Single-Line Comments
Single-line remarks in Python have shown to be effective for providing quick descriptions for
parameters, function definitions, and expressions. A single-line comment of Python is the one
that has a hashtag # at the beginning of it and continues until the finish of the line. If the
comment continues to the next line, add a hashtag to the subsequent line and resume the
conversation. Consider the accompanying code snippet, which shows how to use a single line
comment:
Code
Output:
Everything following the # is omitted. As a result, we may put the program mentioned above in
one line as follows:
Code
1. print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:
This program's output will be identical to the example above. The computer overlooks all content
following #.
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many
ways to create multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments.
Every line with a (#) before it will be regarded as a single-line comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Because Python overlooks string expressions that aren't allocated to a variable, we can utilize
them as comments.
Code
We can observe that on running this code, there will be no output; thus, we utilize the strings
inside triple quotes(""") as multi-line comments.
Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__ attribute.
Code
Output:
1. a = 5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
Play Video
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data-types. We will
discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Output:
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items
of different data types. The items of the tuple are separated with a comma (,) and enclosed in
parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores a specific value. Key can hold any primitive data type, whereas
value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.
Output:
Implicit character data conversion is the term used in Python when a data type conversion occurs
whether during compilation or even during runtime. We do not need to manually change the file
format into some other type of data because Python performs the implicit character data
conversion. Throughout the tutorial, we have seen numerous examples of this type of data type
conversion.
Without user input, the Programming language automatically changes one data type to another
in implicit shift of data types.
1. x = 20
2. print("x type:",type(x)
3. y = 0.6
4. print("y type:",type(y))
5. a = x + y
6. print(a)
7. print("z type:",type(z))
Output:
As we can see, while one variable, x, is only of integer type and the other, y, is of float type, the
data type of "z" was automatically transformed to the "float" type. Due to type promotion, which
enables operations by transforming raw data it in to a wider-sized type of data without any
information loss, the float value is instead not turned into an integer. This is a straightforward
instance of Python's Implicit type conversion.
The result variable was changed into to the float dataset rather than the int data type since doing
so would have required the compiler to eliminate the fractional element, which would have
resulting in data loss. To prevent data loss, Python always translates smaller data types into
larger data types.
We may lose the decimal portion of the report if the variable percentage's data type is integer.
Python automatically converts percentage data to float type, which can store decimal values, to
prevent this data loss.
Explicit Type Conversion:
Let us say we want to change a number from a higher data type to a lower data type. Implicit
type conversion is ineffective in this situation, as we observed in the previous section. Explicit
type conversion, commonly referred to as type casting, now steps in to save the day. Using built-
in Language functions like str() to convert to string form and int() to convert to integer type, a
programmer can explicitly change the data form of an object by changing it manually.
The user can explicitly alter the data type in Python's Explicit Type Conversion according to their
needs. Since we are compelled to change an expression into a certain data type when doing
express type conversion, there is chance of data loss. Here are several examples of explicit type
conversion.
o The function int(a, base) transforms any data type to an integer. If the type of data is a
string, "Base" defines the base wherein string is.
o float(): You can turn any data type into a floating-point number with this function.
Output:
Output:
7. The set() function, which converts a type to a set, returns the set.
8. The list() function transforms any data type into a list type.