Python Unit - I - Complete
Python Unit - I - Complete
Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing it.
The interpreter binds the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data
types.
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'>
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored as
an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every single
one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a
place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
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:
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so
on. An integer can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition
operator.
Example - 1
Output:
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put
away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Example:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the curly
braces and separated by a comma to create the set or the built-in function set() is used to create
the set. It can contain different kinds of values.
Output:
Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a symbol that performs a
specific operation between two operands, according to one definition. Operators serve as the
foundation upon which logic is constructed in a program in a particular programming language.
In every programming language, some operators perform several tasks. Same as other
languages, Python also has some operators, and these are given below -
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 operators used between two operands for a particular operation. There are many
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
- (Subtraction) It is used to subtract the second operand from the first operand. If the 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 = 4
(Multiplication) => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Comparison operators mainly use for comparison purposes. Comparison operators compare
the values of the two operands and return a true or false Boolean value in accordance. The
example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the
works of the operators.
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.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Using the assignment operators, the right expression's value is assigned to the left operand.
There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below
table, we explain the works of the 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.
Program Code:
Now we give code examples of Assignment operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>). 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
10. Let, Binary of x = 0101
11. Binary of y = 1000
12. Bitwise OR = 1101
13. 8 4 2 1
14. 1 1 0 1 = 8 + 4 + 1 = 13
15.
16. Bitwise AND = 0000
17. 0000 = 0
18.
19. Bitwise XOR = 1101
20. 8 4 2 1
21. 1 1 0 1 = 8 + 4 + 1 = 13
22. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
23. ~x = -6
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location are 1.
and) 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 xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit
will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the
value of the left operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. In the case of logical AND, if the first one
is 0, it does not depend upon the second one. In the case of logical OR, if the first one is 1, it
does not depend on the second one. Python supports the following logical operators. In the
below table, we explain the works of the logical operators.
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.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
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).
Program Code:
Now we give code examples of Membership operators in Python. The code is given below -
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Identity Operators
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to
be true.
Program Code:
Now we give code examples of Identity operators in Python. The code is given below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c = a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then
the output is given below -
True
False
False
True
True
False
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).
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.
This tutorial will give you a basic overview of all Python keywords and a detailed discussion
of some important keywords that are frequently used.
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.
Assigning a particular meaning to Python keywords means you can't use them for other
purposes in our code. You'll get a message of SyntaxError if you attempt to do the same. If you
attempt to assign anything to a built-in method or type, you will not receive a SyntaxError
message; however, it is still not a smart idea.
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 distinct versions of Python, the preceding keywords might be changed. Some extras may be
introduced, while others may be deleted. By writing the following statement into the coding
window, you can anytime retrieve the collection of keywords in the version you are working
on.
Code
Python Comments
We'll study how to write comments in our program in this article. We'll also learn about single-
line comments, multi-line comments, documentation strings, and other Python comments.
We may wish to describe the code we develop. We might wish to take notes of why a section
of script functions, for instance. We leverage the remarks to accomplish this. Formulas,
procedures, and sophisticated business logic are typically explained with comments. The
Python interpreter overlooks the remarks and solely interprets the script when running a
program. Single-line comments, multi-line comments, and documentation strings are the 3
types of comments in Python.
Our code is more comprehensible when we use comments in it. It assists us in recalling why
specific sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other
code sections. This simple technique stops some lines from running or creates a fast pseudo-
code for the program.
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: