Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Python Unit - I - Complete

Uploaded by

kashish verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Unit - I - Complete

Uploaded by

kashish verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Python Data Types

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:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three kinds of numerical data.

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.

The Python string is demonstrated in the following example.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

Look at the following illustration of string handling.

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

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 (*).

Look at the following example.

Example:

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple

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:

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary

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.

Look at the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean

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.

Look at the following example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

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.

Look at the following example.

1. # Creating Empty set


2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

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.

Consider the following table for a detailed explanation of arithmetic 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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
9. print('Floor division of two numbers:',a//b)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -

Addition of two numbers: 38


Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5
Comparison operator

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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('Two numbers are equal or not:',a==b)
4. print('Two numbers are not equal or not:',a!=b)
5. print('a is less than or equal to b:',a<=b)
6. print('a is greater than or equal to b:',a>=b)
7. print('a is greater b:',a>b)
8. print('a is less than b:',a<b)

Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -

Two numbers are equal or not: False


Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
Assignment Operators

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

= It assigns the value of the right expression to the left operand.

+= 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 -

1. a = 32 # Initialize the value of a


2. b = 6 # Initialize the value of b
3. print('a=b:', a==b)
4. print('a+=b:', a+b)
5. print('a-=b:', a-b)
6. print('a*=b:', a*b)
7. print('a%=b:', a%b)
8. print('a**=b:', a**b)
9. print('a//=b:', a//b)

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 -

1. a = 5 # initialize the value of a


2. b = 6 # initialize the value of b
3. print('a&b:', a&b)
4. print('a|b:', a|b)
5. print('a^b:', a^b)
6. print('~a:', ~a)
7. print('a<<b:', a<<b)
8. print('a>>b:', a>>b)

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 -

1. a = 5 # initialize the value of a


2. print(Is this statement true?:',a > 3 and a < 5)
3. print('Any one statement is true?:',a > 3 or a < 5)
4. print('Each statement is true then return False and vice-
versa:',(not(a > 3 and a < 5)))

Output:

Now we give code examples of Bitwise operators in Python. The code is given below -

Is this statement true?: False


Any one statement is true?: True
Each statement is true then return False and vice-versa: True
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).

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 -

Is value Present? True


Is value not Present? True

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

** Overall other operators employed in the expression, the exponent operator


is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and the multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than, greater then
equal to).

<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators


in not in Membership operators

not or and Logical operators

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.

Introducing 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.

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.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

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

1. # Python program to demonstrate the application of iskeyword()


2. # importing keyword library which has lists
3. import keyword
4.
5. # displaying the complete list using "kwlist()."
6. print("The set of keywords in this version is: ")
7. print( keyword.kwlist )

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.

Introduction to 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.

Advantages of Using Comments

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.

Below are some of the most common uses for comments:

o Readability of the Code


o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code
Types of Comments in Python

In Python, there are 3 types of comments. They are described below:

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

1. # This code is to show an example of a single-line comment


2. print( 'This statement does not have a hashtag before it' )

Output:

This statement does not have a hashtag before it

You might also like