Unit 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Unit 1 Notes

o Desktop Applications
Python Introduction o Console-based Applications
Python is a general purpose, dynamic, high level, and o Mobile Applications
interpreted programming language. It supports Object o Software Development
Oriented programming approach to develop applications. o Artificial Intelligence
It is simple and easy to learn and provides lots of high- o Web Applications
level data structures. o Enterprise Applications
o 3D CAD Applications
Python's syntax and dynamic typing with its interpreted o Machine Learning
nature make it an ideal language for scripting and rapid o Computer Vision or Image Processing
application development. Applications.
o Speech Recognitions
Python supports multiple programming pattern,
including object-oriented, imperative, and functional or Programming cycle for python
procedural programming styles.
Python's development cycle is dramatically shorter than
Python is not intended to work in a particular area, such that of traditional tools. In Python, there are no compile
as web programming. That is why it is known or link steps -- Python programs simply import modules
as multipurpose programming language because it can be at runtime and use the objects they contain.
used with web, enterprise, 3D CAD, etc.

We don't need to use data types to declare variable


because it is dynamically typed so we can write a=10 to
assign an integer value in an integer variable.

Why learn Python?


Python provides many useful features to the programmer.
These features make it most popular and widely used
language. We have listed below few-essential feature of
Python.

o Easy to use and Learn


o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Open Source Language
o Extensible
o Learn Standard Library Python Features
o GUI Programming Support
o Integrated Python provides lots of features that are listed below.
o Embeddable
o Dynamic Memory Allocation 1) Easy to Learn and Use- Python is easy to learn and
o Wide Range of Libraries and Frameworks use. It is developer-friendly and high level programming
language.
Where is Python used? 2) Expressive Language- Python language is more
Python is a general-purpose, popular programming expressive means that it is more understandable and
language and it is used in almost every technical field. readable.
The various areas of Python use are given below. 3) Interpreted Language- Python is an interpreted
o Data Science language i.e. interpreter executes the code line by line at a
o Date Mining

[By- Prof. Narendra Kumar] Page 1


Unit 1 Notes

time. This makes debugging easy and thus suitable for Python is used to build Business applications like ERP
beginners. and e-commerce systems. Tryton is a high level
4) Cross-platform Language- Python can run equally on application platform.
different platforms such as Windows, Linux, Unix and 6) Console Based Application
Macintosh etc. So, we can say that Python is a portable We can use Python to develop console based applications.
language. For example: IPython.
5) Free and Open Source- Python language is freely 7) Audio or Video based Applications
available at official web address. The source-code is also Python is awesome to perform multiple tasks and can be
available. Therefore it is open source. used to develop multimedia applications. Some of real
6) Object-Oriented Language- Python supports object applications are: Tim Player, cplay etc.
oriented language and concepts of classes and objects 8) 3D CAD Applications
come into existence. To create CAD application Fandango is a real application
7) Extensible- It implies that other languages such as which provides full features of CAD.
C/C++ can be used to compile the code and thus it can be 9) Enterprise Applications
used further in our python code. Python can be used to create applications which can be
8) Large Standard Library- Python has a large and broad used within an Enterprise or an Organization. Some real
library and prvides rich set of module and functions for time applications are: OpenErp, Tryton, Picalo etc.
rapid application development. 10) Applications for Images
9) GUI Programming Support- Graphical user Using Python several applications can be developed for
interfaces can be developed using Python. image. Applications developed are: VPython, Gogh,
10) Integrated- It can be easily integrated with languages imgSeek etc.
like C, C++, JAVA etc.
Python Applications Installation on Windows
Visit the link https://www.python.org/downloads/ to download the
1) Web Applications latest release of Python.
We can use Python to develop web applications. It
provides libraries to handle internet protocols such as Step - 1: Select the Python's version to download.
HTML and XML, JSON, Email processing, request,
beautiful Soup, Feed parser etc. It also provides
Frameworks such as Django, Pyramid, Flask etc to design
and develop web based applications. Some important
developments are: Python Wiki Engines, Pocoo, Python
Blog Software etc.
2) Desktop GUI Applications
Python provides Tk GUI library to develop user interface
in python based application. Some other useful toolkits
wxWidgets, Kivy, pyqt that are useable on several
platforms. The Kivy is popular for writing multi touch
applications.
3) Software Development
Python is helpful for software development process. It
works as a support language and can be used for build
Step - 2: Click on the Install Now
control and management, testing etc.
4) Scientific and Numeric Double-click the executable file, which is downloaded; the
Python is popular and widely used in scientific and following window will open. Select Customize installation and
numeric computing. Some useful library and package are proceed. Click on the Add Path check box, it will set the Python
SciPy, Pandas, IPython etc. SciPy is group of packages of path automatically.
engineering, science and mathematics.
5) Business Applications

[By- Prof. Narendra Kumar] Page 2


Unit 1 Notes

 Jupyter Notebook.
 Eclipse + PyDev + LiClipse.
 GNU Emacs.
PayCharm is a cross-platform IDE used for Python
programming. It is one of the best Python IDE editor that
can be used on Windows, macOS, and Linux. This
software contains API that can be used by the developers
to write their own Python plugins so that they can extend
the basic functionalities.

Spyder is a scientific integrated development


environment written in Python. This software is designed
We can also click on the customize installation to choose desired for and by scientists who can integrate with Matplotlib,
location and features. Other important thing is install launcher for SciPy, NumPy, Pandas, Cython, IPython, SymPy, and
the all user must be checked.
other open-source software.
Step - 3 Installation in Process
IDLE (Integrated Development and Learning
Environment) is a default editor that comes with
Python. It is one of the best Python IDE software which
helps a beginner to learn Python easily. IDLE software
package is optional for many Linux distributions. The tool
can be used on Windows, macOS, and Unix.

Visual Studio Code (VS Code) is an open-source


environment developed by Microsoft. It is one of the best
Python IDE for Windows that can be used for Python
development.

 Visual Studio Code provides:


 syntax highlighting,
Now, try to run python on the command prompt. Type the  bracket-matching,
command python -version in case of python3.  auto-indentation,
 box-selection,
Why IDE is used for Python?  built-in support for IntelliSense code completion,
 rich semantic code understanding and navigation,
Python code editors are designed for the developers to  code refactoring tools,
code and debug program easily. Using these Python
IDEs(Integrated Development Environment), you can Basic Fundamentals:
manage a large codebase and achieve quick deployment. i)Tokens and their types.
ii) Comments
Developers can use these editors to create desktop or web a)Tokens:
application. The Python IDEs can also be used by o Tokens can be defined as a punctuator mark,
DevOps engineers for continuous Integration. reserved words and each individual word in a
statement.
 PyCharm. o Token is the smallest unit inside the given
 Visual Studio Code. program.
 Sublime Text. There are following tokens in Python:
 Vim. o Keywords.
 Atom. o Identifiers.

[By- Prof. Narendra Kumar] Page 3


Unit 1 Notes

o Literals. 2) Using triple quotation marks:-


o Operators. Example:
1. str2='''''welcome
o Python Keywords 2. to
o Python Keywords are special reserved words that convey 3. SSSIT'''
a special meaning to the compiler/interpreter. Each 4. print str2
keyword has a special meaning and a specific operation. Output:
These keywords can't be used as a variable. Following is welcome
the List of Python Keywords.
to
SSSIT
True False None and as II. Numeric literals:
Numeric Literals are immutable. Numeric literals can
asset def class continue break belong to following four different numerical types.
Int(signed Long(long float(floa Complex(c
else finally elif del except integers) integers) ting omplex)
point)

global for if from import Numbers( Integers of Real In the form


can be both unlimited numbers of a+bj
raise try or return pass positive and size with both where a
negative) followed by integer and forms the
with no lowercase fractional real part and
nonlocal in not is lambda fractional or part eg: - b forms the
part.eg: 100 uppercase L 26.2 imaginary
eg: part of the
Python Literals 87032845L complex
Python Literals can be defined as data that is given in a number. eg:
variable or constant. 3.14j
Python supports the following literals: Example - Numeric Literals
1. String literals: 1. x = 0b10100 #Binary Literals
String literals can be formed by enclosing a text in the 2. y = 100 #Decimal Literal
quotes. We can use both single as well as double quotes to 3. z = 0o215 #Octal Literal
create a string. 4. u = 0x12d #Hexadecimal Literal
Example: 5. #Float Literal
1. "Aman" , '12345' 6. float_1 = 100.5
Types of Strings: 7. float_2 = 1.5e2
There are two types of Strings supported in Python: 8. #Complex Literal
a) Single-line String- Strings that are terminated within a 9. a = 5+3.14j
single-line are known as Single line Strings. 10. print(x, y, z, u)
Example: 11. print(float_1, float_2)
1. text1='hello' 12. print(a, a.imag, a.real)
b) Multi-line String - A piece of text that is written in Output:
multiple lines is known as multiple lines string. 20 100 141 301
There are two ways to create multiline strings: 100.5 150.0
1) Adding black slash at the end of each line. (5+3.14j) 3.14 5.0
Example:
1. text1='hello\ III. Boolean literals:
2. user' A Boolean literal can have any of the two values: True or
3. print(text1) False.
'hellouser'

[By- Prof. Narendra Kumar] Page 4


Unit 1 Notes

Example - Boolean Literals The sum is: 15


1. x = (1 == True)
2. y = (2 == False) Docstrings Python Comment
3. z = (3 == True)
4. a = True + 10 The docstring comment is mostly used in the module, function,
5. b = False + 10 class or method. It is a documentation Python string. We will
6. print("x is", x) explain the class/method in further tutorials.
7. print("y is", y) Example:
1. def intro():
8. print("z is", z) 2. """
9. print("a:", a) 3. This function prints Hello Narendra
10. print("b:", b) 4. """
Output: 5. print("Hi Narendra")
x is True 6. intro()
y is False Output:
Hello C
z is False
a: 11
b: 10
IV. Special literals.
Python Operators
The operator can be defined as a symbol which is responsible for a
particular operation between two operands. Operators are the
Python Comments pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators,
Python provides the single-lined Python comment. To which are described as follows.
o Arithmetic operators
apply the comment in the code we use the hash(#) at the
o Comparison operators
beginning of the statement or code. o Assignment Operators
1. # This is the print statement o Logical Operators
print("Hello Python") o Bitwise Operators
Here we have written comment over the print statement o Membership Operators
using the hash(#). It will not affect our print statement. o Identity Operators
Arithmetic Operators
Multiline Python Comment Arithmetic operators are used to perform arithmetic operations
between two operands. It includes + (addition), - (subtraction),
We must use the hash (#) at the beginning of every line of *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.
code to apply the multiline Python comment. Consider the
Consider the following table for a detailed explanation of
following example. arithmetic operators.

1. # First line of the comment Operator Description


2. # Second line of the comment
+ (Addition) It is used to add two operands. For
Example: example, if a = 20, b = 10 => a+b =
30
1. # Variable a holds value 5
2. # Variable b holds value 10 - (Subtraction) It is used to subtract the second
3. # Variable c holds sum of a and b operand from the first operand. If the
4. # Print the result first operand is less than the second
5. a=5 operand, the value results negative.
6. b = 10 For example, if a = 20, b = 10 => a -
7. c = a+b b = 10
8. print("The sum is:", c)
/ (divide) It returns the quotient after dividing
Output: the first operand by the second
operand. For example, if a = 20, b =

[By- Prof. Narendra Kumar] Page 5


Unit 1 Notes

10 => a/b = 2.0 = It assigns the value of the right expression to


the left operand.
* It is used to multiply one operand
(Multiplicatio with the other. For example, if a = += It increases the value of the left operand by
n) 20, b = 10 => a * b = 200 the value of the right operand and assigns
the modified value back to left operand. For
% (reminder) It returns the reminder after dividing example, if a = 10, b = 20 => a+ = b will be
the first operand by the second equal to a = a+ b and therefore, a = 30.
operand. For example, if a = 20, b =
10 => a%b = 0 -= It decreases the value of the left operand by
the value of the right operand and assigns
** (Exponent) It is an exponent operator the modified value back to left operand. For
represented as it calculates the first example, if a = 20, b = 10 => a- = b will be
operand power to the second equal to a = a- b and therefore, a = 10.
operand.
*= It multiplies the value of the left operand by
// (Floor It gives the floor value of the the value of the right operand and assigns
division) quotient produced by dividing the the modified value back to then the left
two operands. operand. For example, if a = 10, b = 20 =>
a* = b will be equal to a = a* b and
Comparison operator therefore, a = 200.
Comparison operators are used to comparing the value of the two
operands and returns Boolean true or false accordingly. The %= It divides the value of the left operand by the
comparison operators are described in the following table. value of the right operand and assigns the
reminder back to the left operand. For
Operator Description example, if a = 20, b = 10 => a % = b will
be equal to a = a % b and therefore, a = 0.
== If the value of two operands is equal, then **= a**=b will be equal to a=a**b, for example,
the condition becomes true. if a = 4, b =2, a**=b will assign 4**2 = 16
to a.
!= If the value of two operands is not equal,
then the condition becomes true. //= 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.
<= If the first operand is less than or equal to
the second operand, then the condition
becomes true.
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of
>= If the first operand is greater than or equal the two operands. Consider the following example.
to the second operand, then the condition For example,
becomes true. 1. if a = 7
2. b=6
> If the first operand is greater than the 3. then, binary (a) = 0111
second operand, then the condition 4. binary (b) = 0011
becomes true. 5.
6. hence, a & b = 0011
If the first operand is less than the second 7. a | b = 0111
<
operand, then the condition becomes true. 8. a ^ b = 0100
9. ~ a = 1000
Assignment Operators
The assignment operators are used to assign the value of the right Operator Description
expression to the left operand. The assignment operators are
described in the following table.
& (binary and) If both the bits at the same place in
Opera Description two operands are 1, then 1 is copied
to the result. Otherwise, 0 is copied.
tor

[By- Prof. Narendra Kumar] Page 6


Unit 1 Notes

| (binary or) The resulting bit will be 0 if both the operand


bits are zero; otherwise, the resulting is not found in the second operand
bit will be 1. (list, tuple, or dictionary).

^ (binary xor) The resulting bit will be 1 if both the Identity Operators
bits are different; otherwise, the The identity operators are used to decide whether an element
resulting bit will be 0. certain class or type.
~ (negation) It calculates the negation of each bit Operator Description
of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.
is It is evaluated to be true if the
<< (left shift) The left operand value is moved left reference
by the number of bits present in the present at both sides point to the
right operand. same object.

>> (right shift) The left operand is moved right by is not It is evaluated to be true if the
the number of bits present in the reference
right operand. present at both sides do not point
to the same object.
Logical Operators
The logical operators are used primarily in the expression Operator Precedence
evaluation to make a decision. Python supports the following The precedence of the operators is essential to find out since it
logical operators. enables us to know which operator should be evaluated first. The
precedence table of the operators in Python is given below.
Operat Description
or Operator Description

and If both the expression are true, then the ** The exponent operator is given priority
condition will be true. If a and b are the over all the others used in the
two expressions, a → true, b → true => a expression.
and b → true.
~+- The negation, unary plus, and minus.
or If one of the expressions is true, then the
condition will be true. If a and b are the * / % // The multiplication, divide, modules,
two expressions, a → true, b → false => a reminder, and floor division.
or b → true.
+- Binary plus, and minus
not If an expression a is true, then not (a)
will be false and vice versa. >> << Left shift. and right shift

Membership Operators & Binary and.


Python membership operators are used to check the membership
^| Binary xor, and or
of value inside a Python data structure. If the value is present in
the data structure, then the resulting value is true otherwise it
<= < > >= Comparison operators (less than, less
returns false.
than equal to, greater than, greater then
equal to).
Operator Description
<> == != Equality operators.
in It is evaluated to be true if the first
operand = %= /= //= - Assignment operators
is found in the second operand (list, tuple, = +=
or dictionary). *= **=

not in It is evaluated to be true if the first is is not Identity operators

[By- Prof. Narendra Kumar] Page 7


Unit 1 Notes

in not in Membership operators the in-built functions for type conversion, along with their
descriptions.
not or and Logical operators
Function Description

int(y [base]) It converts y to an integer, and Base specifies


Type Conversion in Python with the number base. For example, if you want to
convert the string in decimal number then
Examples you’ll use 10 as base.

The process of converting a Python data type into another float(y) It converts y to a floating-point number.
data type is known as type conversion. There are mainly
complex(real It creates a complex number.
two types of type conversion methods in Python, namely,
[imag])
implicit type conversion and explicit type conversion.
In this module, we will go through the following topics: str(y) It converts y to a string.

 Implicit Type Conversion in Python tuple(y) It converts y to a tuple.


 Explicit Type Conversion in Python
list(y) It converts y to a list.
 Key Points to Remember While performing Type
Conversion in Python set(y) It converts y to a set.

So, without any further delay, let’s get started. dict(y) It creates a dictionary and y should be a
sequence of (key, value) tuples.
Implicit Type Conversion in Python
ord(y) It converts a character into an integer.
In Python, when the data type conversion takes place
during compilation or during the run time, then it’s hex(y) It converts an integer to a hexadecimal string.
called an implicit data type conversion. Python handles
oct(y) It converts an integer to an octal string
the implicit data type conversion, so we don’t have to
explicitly convert the data type into another data type. We Now that we know the in-built functions provided by
have seen various examples of this kind of data type Python that are used for explicit type conversion, let’s see
conversion throughout the tutorial. the syntax for explicit type conversion:
Python Interpreter is able to convert the data type of the (required_data type)(expression)
resultant variable or not.
Explicit type conversion in Python.
Ex. a = 5
# adding string and integer data types using explicit type
b = 5.5 conversion
sum = a + b a = 100
print (sum) b = “200”
print (type (sum)) #type() is used to display the data type result1 = a + b
of a variable
b = int(b)
Output: result2 = a + b
10.5
print(result2)
<class ‘float’>
Output:
Explicit Type Conversion in Python Traceback (most recent call last):
Explicit type conversion is also known as type casting. File “”, line 1, in
Explicit type conversion takes place when the TypeError: unsupported operand type(s) for +: ‘int’ and
programmer clearly and explicitly defines the same in the ‘str’
program. For explicit type conversion, there are some in-
300
built Python functions. Following table contains some of

[By- Prof. Narendra Kumar] Page 8


Unit 1 Notes

Output:
Python Data Types
The type of a <class 'int'>
A variable can hold different types of values. For example, a The type of b <class 'float'>
person's name must be stored as a string whereas its id must be The type of c <class 'complex'>
stored as an integer. c is complex number: True

Python provides various standard data types that define the Python supports three types of numeric data.
storage method on each of them. The data types defined in
Python are given below. 1. Int - Integer value can be any length such as integers
10, 2, 29, -20, -150 etc. Its value belongs to int
1. Numbers 2. Float - Float is used to store floating-point numbers
2. Sequence Type like 1.9, 9.902, 15.2, etc.
3. Boolean 3. Complex - A complex number contains an ordered
4. Set pair, i.e., x + iy where x and y denote the real and
imaginary parts, respectively. The complex numbers
5. Dictionary like 2.14j, 2.0 + 2.3j, etc.

Numbers Sequence Type


Number stores numeric values. The integer, float, and complex String
values belong to a Python Numbers data-type. Python provides
the type() function to know the data-type of the variable. The string can be defined as the sequence of characters
Similarly, the isinstance() function is used to check an object represented in the quotation marks. In Python, we can use
belongs to a particular class. single, double, or triple quotes to define a string.
Python creates Number objects when a number is assigned to a In the case of string handling, the operator + is used to
variable. For example; 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
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
Consider the following example of string handling.
Example - 2
1. str1 = 'hello javatpoint' #string str1
1. a=5
2. str2 = ' how are you' #string str2
2. print("The type of a", type(a))
3. print (str1[0:2]) #printing first two character using slice operat
3. b = 40.5
or
4. print("The type of b", type(b))
4. print (str1[4]) #printing 4th character of the string
5. c = 1+3j
5. print (str1*2) #printing the string twice
6. print("The type of c", type(c))
6. print (str1 + str2) #printing the concatenation of str1 and str2
7. print(" c is a complex number", isinstance(1+3j,complex))

[By- Prof. Narendra Kumar] Page 9


Unit 1 Notes

Output: 2. # Checking type of tup


he 3. print (type(tup))
o #Printing the tuple
hello javatpointhello javatpoint 4. print (tup)
hello javatpoint how are you 5. # Tuple slicing
6. print (tup[1:])
List 7. print (tup[0:1])
8. # Tuple concatenation using + operator
Python Lists are similar to arrays in C. However, the list can9. print (tup + tup)
contain data of different types. The items stored in the list are10. # Tuple repatation using * operator
separated with a comma (,) and enclosed within square brackets11. print (tup * 3)
[ ]. 12. # Adding value to tup. It will throw an error.
13. t[2] = "hi"
We can use slice [:] operators to access the data of the list. The Output:
concatenation operator (+) and repetition operator (*) works
with the list in the same way as they were working with the <class 'tuple'>
strings. ('hi', 'Python', 2)
('Python', 2)
Ex. ('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
1. list1 = [1, "hi", "Python", 2] ('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
2. #Checking type of given list
3. print(type(list1)) Traceback (most recent call last):
4. #Printing the list1 File "main.py", line 14, in <module>
5. print (list1) t[2] = "hi";
6. # List slicing TypeError: 'tuple' object does not support item assignment
7. print (list1[3:])
8. # List slicing Dictionary
9. print (list1[0:2]) Dictionary is an unordered set of a key-value pair of items. It is
10. # List Concatenation using + operator like an associative array or a hash table where each key stores a
11. print (list1 + list1) specific value. Key can hold any primitive data type, whereas
12. # List repetation using * operator value is an arbitrary Python object.
13. print (list1 * 3)
The items in the dictionary are separated with the comma (,)
Output: and enclosed in the curly braces {}.

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


[2] 2. # Printing dictionary
[1, 'hi'] 3. print (d)
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] 4. # Accesing value using keys
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2] 5. print("1st name is "+d[1])
6. print("2nd name is "+ d[4])
Tuple 7. print (d.keys())
A tuple is similar to the list in many ways. Like lists, tuples 8. print (d.values())
also contain the collection of the items of different data types. Output:
The items of the tuple are separated with a comma (,) and
enclosed in parentheses (). 1st name is Jimmy
2nd name is mike
A tuple is a read-only data structure as we can't modify the size {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
and value of the items of a tuple. dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Let's see a simple example of the tuple.

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

[By- Prof. Narendra Kumar] Page 10


Unit 1 Notes

2. How to construct expressions.


Boolean How to create an expressions
Boolean type provides two built-in values, True and False.
Python expressions only contain identifiers, literals, and operators.
These values are used to determine the given statement true or So, what are these?
false. It denotes by the class bool. True can be represented by Identifiers: Any name that is used to define a class, function,
any non-zero value or 'T' whereas false can be represented by variable module, or object is an identifier. Literals: These are
the 0 or 'F'. Consider the following example. language-independent terms in Python and should exist
independently in any programming language. In Python, there are
1. # Python program to check the boolean type the string literals, byte literals, integer literals, floating point
2. print(type(True)) literals, and imaginary literals. Operators: In Python you can
3. print(type(False)) implement the following operations using the corresponding
4. print(false) tokens.
5. Output: Operator Token
6. <class 'bool'>
7. <class 'bool'> add +
8. NameError: name 'false' is not defined
subtract -
Set multiply *
Python Set is the unordered collection of the data type. It is
iterable, mutable(can modify after creation), and has unique power **
elements. In set, the order of the elements is undefined; it may Integer Division /
return the changed sequence of the element. The set is created
by using a built-in function set(), or a sequence of elements is remainder %
passed in the curly braces and separated by the comma. It can
contain various types of values. Consider the following decorator @
example.
Binary left shift <<
1. # Creating Empty set Binary right shift >>
2. set1 = set()
3. set2 = {'James', 2, 3,'Python'} and &
4. #Printing Set value
or \
5. print(set2)
6. # Adding element to the set Binary Xor ^
7. set2.add(10)
8. print(set2) Binary ones complement ~
9. #Removing element from the set
10. set2.remove(2) Less than <
11. print(set2) Greater than >
12. Output:
13. {3, 'Python', 'James', 2} Less than or equal to <=
14. {'Python', 'James', 3, 2, 10}
15. {'Python', 'James', 3, 10} Greater than or equal to >=

Check equality ==

Python Expressions: Check not equal !=


Expressions are representations of value. They are different from
statement in the fact that statements do something while
expressions are representation of value. For example any string is
also an expressions since it represents the value of the string as Types of python expressions:
well.
Python has some advanced constructs through which you can
represent values and hence these constructs are also called List comprehension
expressions. The syntax for list comprehension is shown below:
In this tutorial you will get to know about:
1. What are expressions in Python [ compute(var) for var in iterable ]

[By- Prof. Narendra Kumar] Page 11


Unit 1 Notes

For example, the following code will get all the number within 10
and put them in a list.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }

For example, the following code will get all the numbers within 5
as the keys and will keep the corresponding squares of those
numbers as the values.
>>> {x:x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Generator expression
The syntax for generator expression is shown below:
( compute(var) for var in iterable )

For example, the following code will initialize a generator object


that returns the values within 10 when the object is called.
>>> (x for x in range(10))
<generator object <genexpr> at 0x7fec47aee870>
>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Conditional Expressions
You can use the following construct for one-liner conditions:
true_value if Condition else false_value

Example:
>>> x = "1" if True else "2"
>>> x
'1'

[By- Prof. Narendra Kumar] Page 12

You might also like