0% found this document useful (0 votes)
3 views29 pages

Unit 1

Uploaded by

kushsevak9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Unit 1

Uploaded by

kushsevak9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

UNIT-1

What is Programming ?

Programming is the process of instructing a computer to perform specific tasks by


providing a set of instructions written in a programming language. It involves creating
algorithms and implementing logic to solve problems or automate processes.

Python was created in the late 1980s by Guido van Rossum.


The first official Python release, Python 0.9.0, was released in February 1991.

Design Philosophy

Python's design philosophy emphasizes readability, making it easy for programmers to


express ideas in code.
It follows the "Zen of Python," a set of guiding principles that promote simplicity, clarity,
and beauty in code

Batteries included

Python is often referred to as a "batteries-included" language, meaning it comes with a


comprehensive standard library.
The standard library provides modules and packages for a wide range of tasks,
reducing the need for external libraries.

General Purpose

Python is a general-purpose language, meaning it can be used for various applications,


from web development and automation to scientific research and machine learning.
Its versatility makes it a top choice for solving a wide range of problems.

Libraries/Community

Python has a vast and active community of developers who contribute to open-source
libraries and frameworks.
Popular libraries like NumPy, Pandas, TensorFlow, Django, and Flask extend Python's
capabilities for specific domains.
The Python community is known for its support and resources, making it easier to find
solutions and assistance when working with Python.

localhost:8888/notebooks/Unit-1_VHA.ipynb 1/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

Why Python for Data Science?

Easy to learn

Python is renowned for its simplicity and readability, making it an accessible language
for both beginners and experienced programmers.
The clean and intuitive syntax reduces the learning curve, allowing data scientists to
focus on data analysis rather than wrestling with the language.

Proximity with Maths

Python offers a wide array of libraries and tools that are specifically designed for data
analysis and scientific computing.
Libraries like NumPy, SciPy, and pandas provide efficient and easy-to-use data
structures and functions for numerical and statistical operations.
Python's compatibility with mathematical operations and libraries makes it a natural fit
for data science tasks.

Community

Python has a thriving and active community of data scientists, analysts, and
developers.
This community contributes to an extensive ecosystem of libraries and resources,
including data visualization tools (Matplotlib, Seaborn), machine learning frameworks
(Scikit-Learn, TensorFlow), and data manipulation libraries (Pandas).
The availability of resources, forums, and tutorials makes it easy for data scientists to
find help, collaborate, and stay updated with the latest developments in the field.

1. Python Output
In Python, when you write something like vishal(), you are indeed calling a function named
vishal. The parentheses () are used to indicate that the function is being invoked or called.
To be more specific, vishal() is the syntax used to call a function without passing any
arguments.

localhost:8888/notebooks/Unit-1_VHA.ipynb 2/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [14]: 1 help(print)

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdou
t.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

In [7]: 1 # Python is a case sensitive language


2 print('Hello World')

Hello World

In [8]: 1 print('INDIA')

INDIA

In [9]: 1 print(INDIA)

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
~\AppData\Local\Temp\ipykernel_7452\1453359074.py in <module>
----> 1 print(INDIA)

NameError: name 'INDIA' is not defined

In [10]: 1 print(7)

In [11]: 1 print(7.7)

7.7

In [12]: 1 print(True)

True

In [13]: 1 print('hello',1,4,5.5,True,False)

hello 1 4 5.5 True False

localhost:8888/notebooks/Unit-1_VHA.ipynb 3/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [15]: 1 print('hello',1,4,5.5,True,False,sep="v")

hellov1v4v5.5vTruevFalse

In [16]: 1 print('hello',1,4,5.5,True,False,sep="/")

hello/1/4/5.5/True/False

In [17]: 1 print("hello")
2 print("world")

hello
world

In [18]: 1 print("hello",end=".")
2 print("world")

hello.world

In [20]: 1 print('hello''world')

helloworld

2.Datatype
In [22]: 1 # Integer
2 print(8)
3 # 1*10^308
4 print(1e308)

8
1e+308

In [23]: 1 print(1e308)

1e+308

In [26]: 1 print(-5e307)

-5e+307

In [29]: 1 # Decimal/Float
2 print(8.55)
3 print(1.7e308)

8.55
1.7e+308

localhost:8888/notebooks/Unit-1_VHA.ipynb 4/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [30]: 1 # Decimal/Float
2 print(8.55)
3 print(1.7e309)

8.55
inf

In [31]: 1 # Boolean
2 print(True)
3 print(False)

True
False

In [32]: 1 print(5==5)

True

In [33]: 1 # Text/String
2 print('Hello World')

Hello World

In [34]: 1 # complex
2 print(5+6j)

(5+6j)

In [35]: 1 # List-> C-> Array


2 print([1,2,3,4,5])

[1, 2, 3, 4, 5]

In [36]: 1 # Tuple
2 print((1,2,3,4,5))

(1, 2, 3, 4, 5)

In [37]: 1 # Sets
2 print({1,2,3,4,5})

{1, 2, 3, 4, 5}

In [39]: 1 # Dictionary
2 print({'name':'Vishal','gender':'Male','weight':77})

{'name': 'Vishal', 'gender': 'Male', 'weight': 77}

localhost:8888/notebooks/Unit-1_VHA.ipynb 5/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [54]: 1 # type
2 print(type([1,2,3]))
3 print(type(7))
4 print(type((7)))
5 print(type((7,)))
6 print(type(7.7))
7 print(type("vishal"))
8 print(type({5,1}))
9 print(type({'name':'Vishal','gender':'Male','weight':77}))
10 print(type(5+6j))

<class 'list'>
<class 'int'>
<class 'int'>
<class 'tuple'>
<class 'float'>
<class 'str'>
<class 'set'>
<class 'dict'>
<class 'complex'>

3.variable
A variable is a named storage location in a program's memory that can hold and
manipulate data.

in python,variable do not need to be decleared with any perticular data type

In [56]: 1 # Static Vs Dynamic Typing


2 # Static Vs Dynamic Binding
3 # stylish declaration techniques

In [59]: 1 name = 'Vishal'


2 print(name)
3 a = 5
4 b = 6
5 print(a + b)

Vishal
11

Dynamic Typing
a=5

Static Typing
int a = 5

localhost:8888/notebooks/Unit-1_VHA.ipynb 6/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [61]: 1 # Dynamic Binding


2 a = 5
3 print(a)
4 a = 'nitish'
5 print(a)

5
nitish

Static Binding
int a = 5

In [63]: 1 a = 1
2 b = 2
3 c = 3
4 print(a,b,c)

1 2 3

In [64]: 1 a,b,c = 1,2,3


2 print(a,b,c)

1 2 3

In [65]: 1 a=b=c= 5
2 print(a,b,c)

5 5 5

Comments
In [2]: 1 # this is a comment
2 # second line
3 a = 7
4 b = 6 # like this
5 # second comment
6 print(a+b)
7 """multi
8 line
9 comment"""

13

Out[2]: 'multi \nline\ncomment'

4. Keywords & Identifiers

Reserve keywords in python


localhost:8888/notebooks/Unit-1_VHA.ipynb 7/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook
1 Python Keywords are some predefined and reserved words in Python
that have special meanings. Keywords are used to define the syntax
of the coding. The keyword cannot be used as an identifier,
function, or variable name. All the keywords in Python are written
in lowercase except True,None and False.

In [1]: 1 help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more hel
p.

False break for not


None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield

1 Identifier is a user-defined name given to a variable, function,


class, module, etc. The identifier is a combination of character
digits and an underscore. They are case-sensitive i.e., ‘num’ and
‘Num’ and ‘NUM’ are three different identifiers in python.

Rules for Naming Python Identifiers


It cannot be a reserved python keyword.
It should not contain white space.
It can be a combination of A-Z, a-z, 0-9, or underscore.
It should start with an alphabet character or an underscore ( _ ).
It should not contain any special character other than an underscore ( _ ).

1 Valid identifiers:
2 ​
3 var1
4 _var1
5 _1_var
6 var_1
7 Invalid Identifiers
8 ​
9 !var1
10 1var
11 1_var
12 var#1
13 var 1

In [77]: 1 !var=1

'var' is not recognized as an internal or external command,


operable program or batch file.

localhost:8888/notebooks/Unit-1_VHA.ipynb 8/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [78]: 1 1var=7

File "C:\Users\VISHAL\AppData\Local\Temp\ipykernel_7452\2199671680.py",
line 1
1var=7
^
SyntaxError: invalid syntax

Camel Case

Definition: Each word starts with a capital letter except for the first word.
Example: myVariableName

Snake Case

Definition: Words are separated by underscores.


Example: my_variable_name

Pascal Case

Definition: Similar to camel case but starts with a capital letter.


Example: MyVariableName

5. User Input
In [79]: 1 help(input)

Help on method raw_input in module ipykernel.kernelbase:

raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance


Forward raw_input to frontends

Raises
------
StdinNotImplementedError if active frontend doesn't support stdin.

In [80]: 1 help(eval)

Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)


Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression


or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

localhost:8888/notebooks/Unit-1_VHA.ipynb 9/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [81]: 1 x=input("enter number")


2 print(x)
3 print(type(x))

enter number5
5
<class 'str'>

In [82]: 1 # take input from users and store them in a variable


2 fnum = int(input('enter first number'))
3 snum = int(input('enter second number'))
4 #print(type(fnum),type(snum))
5 # add the 2 variables
6 result = fnum + snum
7 # print the result
8 print(result)
9 print(type(fnum))

enter first number5


enter second number7
12
<class 'int'>

Type Conversion

Implicit in Python:
Implicit actions or conversions happen automatically without the need for explicit
instructions.
Implicit type conversion (coercion) occurs when Python automatically converts data
types for operations.
Python performs implicit actions to make code more readable and user-friendly.

Explicit in Python:
Explicit actions or conversions require specific instructions provided by the
programmer.
Explicit type conversion (casting) is performed when you provide clear and direct
commands for type conversion.
Explicit actions are used when you need precise control and clarity in your code.

In [83]: 1 # Implicitly converts 'a' to a float before addition


2 a = 5
3 b = 2.0
4 result = a + b

localhost:8888/notebooks/Unit-1_VHA.ipynb 10/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [84]: 1 # Explicitly convert the string to an integer


2 num_str = "42"
3 num_int = int(num_str)
4 num_int+b

Out[84]: 44.0

In [85]: 1 # Implicit Vs Explicit


2 print(5+5.6)
3 print(type(5),type(5.6))
4 ​
5 print(4 + '4')

10.6
<class 'int'> <class 'float'>

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
~\AppData\Local\Temp\ipykernel_7452\3295153562.py in <module>
3 print(type(5),type(5.6))
4
----> 5 print(4 + '4')

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [86]: 1 # Explicit
2 # str -> int
3 #int(4+5j)
4 ​
5 # int to str
6 str(5)
7 ​
8 # float
9 float(4)

Out[86]: 4.0

7. Literals
In Python, literals are fixed values or data that are directly used in your code. They
represent constants and can be assigned to variables

String Literals: These are sequences of characters enclosed in single (' '), double ("
"), or triple (''' ''' or """ """) quotes. For example:

localhost:8888/notebooks/Unit-1_VHA.ipynb 11/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [94]: 1 print('1')
2 print('vishal')
3 print('2')
4 print("vishal")
5 print('3')
6 print('''vishal
7 hi''')
8 print('4')
9 print("""vishal
10 hi
11 b2
12 b7
13 d1""")
14 print('5')
15 print("vishal's")
16 print('vishal"s')

1
vishal
2
vishal
3
vishal
hi
4
vishal
hi
b2
b7
d1
5
vishal's
vishal"s

In [95]: 1 print('vishal's')

File "C:\Users\VISHAL\AppData\Local\Temp\ipykernel_7452\927117232.py", l
ine 1
print('vishal's')
^
SyntaxError: invalid syntax

Numeric Literals: These are used to represent numeric values. They include integers,
floating-point numbers, and complex numbers. For example:

In [2]: 1 int_literal = 42
2 float_literal = 3.14
3 complex_literal = 2 + 3j
4 print(int_literal)
5 print(float_literal)
6 print(complex_literal)

42
3.14
(2+3j)

localhost:8888/notebooks/Unit-1_VHA.ipynb 12/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

Boolean Literals: These represent the two Boolean values, True and False

In [3]: 1 bool_literal_true = True


2 bool_literal_false = False
3 print(bool_literal_true)
4 print(bool_literal_false)

True
False

None Literal: The None literal represents the absence of a value or a null value

In [4]: 1 none_literal = None


2 print(none_literal)

None

List Literals: Lists are collections of values, and you can create them using square
brackets.

In [5]: 1 list_literal = [1, 2, 3, 4]


2 print(list_literal)

[1, 2, 3, 4]

Tuple Literals: Tuples are similar to lists but use parentheses for literals.

In [6]: 1 tuple_literal = (1, 2, 3, 4)


2 print(tuple_literal)

(1, 2, 3, 4)

Dictionary Literals: Dictionaries are collections of key-value pairs, and you can
create them using curly braces.

In [7]: 1 dict_literal = {"key1": "value1", "key2": "value2"}


2 print(dict_literal)

{'key1': 'value1', 'key2': 'value2'}

Set Literals: Sets are collections of unique elements and are created using curly
braces with values separated by commas

In [8]: 1 set_literal = {1, 2, 3, 4}


2 print(set_literal)

{1, 2, 3, 4}

localhost:8888/notebooks/Unit-1_VHA.ipynb 13/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

Raw String Literals: A raw string literal is prefixed with 'r' and is used to specify raw
strings that don't escape backslashes.

In [109]: 1 raw_string_literal = r"C:\Users\Username"


2 print(raw_string_literal)

C:\Users\Username

In [110]: 1 raw_string_literal = "C:\Users\Username"


2 print(raw_string_literal)

File "C:\Users\VISHAL\AppData\Local\Temp\ipykernel_7452\3293659636.py",
line 1
raw_string_literal = "C:\Users\Username"
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in p
osition 2-3: truncated \UXXXXXXXX escape

Formatted String Literals (f-strings): Introduced in Python 3.6, f-strings are used for
string formatting by placing an 'f' or 'F' before the string literal.

In [112]: 1 name = "Alice"


2 formatted_string = f"Hello, {name}!"
3 print(formatted_string)

Hello, Alice!

In [113]: 1 #Complex Literal


2 x = 7.14j
3 print(x, x.imag, x.real)

7.14j 7.14 0.0

In [115]: 1 unicode = u"\U0001f600\U0001F606\U0001F923"


2 raw_str = r"raw \n string"
3 print(unicode)

😀😆🤣

In [116]: 1 a = True + 4
2 b = False + 10
3 ​
4 print("a:", a)
5 print("b:", b)

a: 5
b: 10

localhost:8888/notebooks/Unit-1_VHA.ipynb 14/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [118]: 1 k = None
2 a = 5
3 b = 6
4 print(a+b,k)

11 None

In [10]: 1 a = 0b1010 #Binary Literals


2 b = 100 #Decimal Literal
3 c = 0o310 #Octal Literal
4 d = 0x12c #Hexadecimal Literal
5 print(a,b,c,d)

10 100 200 300

None is a special built-in constant that represents the absence of a value or a null
value. It is often used to signify that a variable or object has no assigned value.

When you set a variable to None, you are essentially saying that the variable exists,
but it doesn't contain any meaningful data. This can be useful in various situations,
such as when you want to initialize a variable before assigning a real value to it

Operators in Python
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Membership Operators

Arithmetic Operators

+ (Addition): This operator is used to add two numbers.

In [11]: 1 result = 5 + 3 # result will be 8


2 print(result)

- (Subtraction): Subtracts the right operand from the left


operand.

In [12]: 1 result = 10 - 3 # result is 7


2 print(result)

localhost:8888/notebooks/Unit-1_VHA.ipynb 15/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

* (Multiplication): Multiplies two numbers

In [13]: 1 result = 4 * 6 # result is 24


2 print(result)

24

/ (Division): Divides the left operand by the right operand (float


division).

In [14]: 1 result = 20 / 4 # result is 5.0


2 print(result)

5.0

// (Floor Division): Divides and rounds down the result to the


nearest whole number.

In [15]: 1 result = 20 // 4 # result is 5


2 print(result)

% (Modulus): Divides and returns the remainder.

In [16]: 1 result = 20 % 3 # result is 2 (20 divided by 3 leaves a remainder of 2


2 print(result)

** (Exponentiation): Raises the left operand to the power of the


right operand.

In [17]: 1 result = 2 ** 3 # result is 8 (2 raised to the power of 3)


2 print(result)

Comparison operators
used to compare values and return either True or False based on the comparison.
They play a crucial role in control structures like if statements and loops, as well as in
various conditional expressions and algorithms.

localhost:8888/notebooks/Unit-1_VHA.ipynb 16/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

== (Equal): Compares whether two values are equal. Returns True


if they are equal and False otherwise.

In [18]: 1 result=5==5
2 print(result)

True

In [19]: 1 4.0==4

Out[19]: True

In [20]: 1 4=="4"

Out[20]: False

In [21]: 1 True==1.0

Out[21]: True

In [22]: 1 False==0.0

Out[22]: True

In [23]: 1 True==1

Out[23]: True

!= (Not Equal): Checks if two values are not equal. Returns True if
they are different and False if they are equal.

In [24]: 1 result=5!=5
2 print(result)

False

In [25]: 1 5.0!=5

Out[25]: False

In [26]: 1 5.0!="5"

Out[26]: True

localhost:8888/notebooks/Unit-1_VHA.ipynb 17/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

< (Less Than): Determines if the left operand is less than the right
operand. Returns True if it's true and False otherwise.

In [27]: 1 result=5<4
2 print(result)

False

In [28]: 1 5<True

Out[28]: False

In [29]: 1 False<True

Out[29]: True

> (Greater Than): Checks if the left operand is greater than the
right operand. Returns True if it's true and False otherwise.

In [30]: 1 result=5>4
2 print(result)

True

In [31]: 1 5>True

Out[31]: True

In [32]: 1 False>True

Out[32]: False

In [33]: 1 1>True

Out[33]: False

<= (Less Than or Equal To): Verifies if the left operand is less than
or equal to the right operand. Returns True if it's true and False
otherwise.

In [34]: 1 result=5<=4
2 print(result)

False

In [35]: 1 5<=5

Out[35]: True

localhost:8888/notebooks/Unit-1_VHA.ipynb 18/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

>= (Greater Than or Equal To): Determines if


the left operand is greater than or equal to the
right operand. Returns True if it's true and
False otherwise.
In [36]: 1 result=5>=4
2 print(result)

True

In [37]: 1 5>=4

Out[37]: True

Logical operators
in Python allow you to perform logical operations on boolean values (either True or
False). They are often used to combine or manipulate boolean values to make
decisions in your code.

and (Logical AND): The and operator returns True if both operands
are True. If at least one operand is False, it returns False. It can be
used to check if multiple conditions are met.

In [38]: 1 a = 5 and 8
2 print(a)

In [39]: 1 a=5
2 if a==5 and a!=6:
3 print(a)

In [40]: 1 a=5
2 if a==5 and a==6:
3 print(a)
4 else:
5 print('hi')

hi

localhost:8888/notebooks/Unit-1_VHA.ipynb 19/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [41]: 1 is_sunny = True


2 is_warm = True
3 if is_sunny and is_warm:
4 print("It's a sunny and warm day.")

It's a sunny and warm day.

In [42]: 1 is_raining = True


2 is_cold = False
3 if is_raining and is_cold:
4 print("It's raining and cold.")

In [43]: 1 a= 1 and False


2 print(a)

False

In [44]: 1 a= 0 and True


2 print(a)

or (Logical OR): The or operator returns True if at least one of the


operands is True. It returns False only if both operands are False.
It's useful for situations where you want to check if at least one
condition is met.

In [45]: 1 has_ticket = True


2 has_id = False
3 if has_ticket or has_id:
4 print("You can enter the event.")
5 ​

You can enter the event.

In [46]: 1 a= 5 or 6
2 print(a)

In [47]: 1 a= 0 or 8
2 print(a)

In [48]: 1 a= 8 or 0
2 print(a)

localhost:8888/notebooks/Unit-1_VHA.ipynb 20/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

not (Logical NOT): The not operator is a unary operator that


negates the boolean value of its operand. It returns True if the
operand is False, and False if the operand is True. It's used to
reverse the boolean value.

In [49]: 1 a=True
2 print(not a)

False

In [50]: 1 a=0
2 print(not a)

True

Assignment operators
used to assign values to variables and, in some cases, update the value of a variable
while performing an operation.

= (Assignment): The = operator assigns the value on the right side


to the variable on the left side.

In [51]: 1 x = 5 # Assigns the value 5 to the variable x


2 print(x)

+= (Add and Assign): The += operator adds the value on the right
side to the variable on the left side and assigns the result to the
variable on the left

In [52]: 1 y = 10
2 y += 3 # Equivalent to y = y + 3
3 # y now has the value 13
4 print(y)

13

localhost:8888/notebooks/Unit-1_VHA.ipynb 21/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

-= (Subtract and Assign): The -= operator subtracts the value on


the right side from the variable on the left side and assigns the
result to the variable on the left.

In [53]: 1 z = 15
2 z -= 6 # Equivalent to z = z - 6
3 # z now has the value 9
4 print(z)

*= (Multiply and Assign): The *= operator multiplies the variable on


the left side by the value on the right side and assigns the result
to the variable on the left.

In [54]: 1 a = 4
2 a *= 7 # Equivalent to a = a * 7
3 # a now has the value 28
4 print(a)

28

/= (Divide and Assign): The /= operator divides the variable on the


left side by the value on the right side and assigns the result to
the variable on the left.

In [55]: 1 b = 30
2 b /= 3 # Equivalent to b = b / 3
3 # b now has the value 10.0 (note the float division)
4 print(b)

10.0

//= (Floor Divide and Assign): The //= operator performs floor
division on the variable on the left side by the value on the right
side and assigns the result to the variable on the left.

In [56]: 1 c = 17
2 c //= 5 # Equivalent to c = c // 5
3 # c now has the value 3
4 print(c)

localhost:8888/notebooks/Unit-1_VHA.ipynb 22/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

%= (Modulus and Assign): The %= operator calculates the


remainder when dividing the variable on the left side by the value
on the right side and assigns the remainder to the variable on the
left.

In [57]: 1 d = 25
2 d %= 7 # Equivalent to d = d % 7
3 # d now has the value 4
4 print(d)

**= (Exponentiation and Assign): The **= operator raises the


variable on the left side to the power of the value on the right side
and assigns the result to the variable on the left.

In [58]: 1 e = 2
2 e **= 3 # Equivalent to e = e ** 3
3 # e now has the value 8
4 print(e)

localhost:8888/notebooks/Unit-1_VHA.ipynb 23/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook



localhost:8888/notebooks/Unit-1_VHA.ipynb 24/29
9/29/24, 1:16 PM Unit-1_VHA - Jup ter Notebook

Membership operators
used to check whether a specific value is a member of a sequence or collection, such
as a list, tuple, string, or set. There are two membership operators: in and not in

localhost:8888/notebooks/Unit-1_VHA.ipynb 25/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

in (Membership Operator): The in operator checks if a value exists


in a given sequence or collection. If the value is found in the
sequence, it returns True; otherwise, it returns False.

In [202]: 1 my_list = [1, 2, 3, 4, 5]


2 result = 3 in my_list # True, because 3 is in the list
3 print(result)

True

not in (Membership Operator): The not in operator checks if a


value is not found in a given sequence. If the value is not in the
sequence, it returns True; otherwise, it returns False.

In [203]: 1 # True, because "Goodbye" is not in the string


2 my_string = "Hello, World!"
3 result = "Goodbye" not in my_string

Identity operators in Python are used to compare the


memory locations (identities) of objects rather than
their values.

is (Identity Operator): The is operator checks if two objects are the


same, meaning they share the same memory location. If the
objects have the same identity, it returns True; otherwise, it
returns False

In [205]: 1 x = [1, 2, 3]
2 y = x # y refers to the same object as x
3 result = x is y # True, because x and y are the same object
4 print(result)

True

is not (Identity Operator): The is not operator checks if two


objects are not the same. If the objects do not have the same
identity, it returns True; otherwise, it returns False.

In [206]: 1 a = [1, 2, 3]
2 b = [1, 2, 3] # b is a different object with the same value
3 result = a is not b # True, because a and b are different objects
4 print(result)

True

The Ternary Conditional Operator in Python is


a shorthand way to express conditional
localhost:8888/notebooks/Unit-1_VHA.ipynb 26/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

statements, allowing you to write a simple


conditional expression in a single line. It's
also known as the conditional expression.
The general syntax of the ternary conditional
operator is as follows:
value_if_true if condition else value_if_false
condition is a boolean expression that is evaluated.
If the condition is True, the expression returns value_if_true.
If the condition is False, the expression returns value_if_false

In [208]: 1 age = 18
2 status = "Adult" if age >= 18 else "Minor"
3 print(status)

Adult

Precedence determines the order in which operators are evaluated in an expression.


Operators with higher precedence are evaluated first. If two operators have the same
precedence, then associativity determines the order of evaluation. Operators with
left-to-right associativity are evaluated from left to right, while operators with right-to-
left associativity are evaluated from right to left

localhost:8888/notebooks/Unit-1_VHA.ipynb 27/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

In [211]: 1 result = 5 + 3 * 2**3**2


2 print(result)

1541

In [214]: 1 # Result will be True (relational operators are evaluated left to right
2 x = 10
3 y = 15
4 result = x < y or x == y

In [216]: 1 a = True
2 b = False
3 c = True
4 result = a and b or c
5 # Result will be True (logical operators have precedence)
6 print(result)

True

In [7]: 1 result = 2**3 + 10 / 2 - 1 < 5 and (


2 7 or 3) != 6 or "Python" in ["Java", "Python", "C++"]
3 print(result)

True

In [4]: 1 result = (8 % 3) ** 2 +(1 > 10 or


2 (not True and (3 in [1, 2, 3])) or "hello" != "world" or (5 // 2) + 1 =
3 print(result)

In [1]: 1 5 or 1/0

Out[1]: 5

In [2]: 1 1/0 or 6

--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
~\AppData\Local\Temp\ipykernel_7964\2162312769.py in <module>
----> 1 1/0 or 6

ZeroDivisionError: division by zero

In [ ]: 1 ​

localhost:8888/notebooks/Unit-1_VHA.ipynb 28/29
9/29/24, 1:16 PM Unit-1_VHA - Jupyter Notebook

localhost:8888/notebooks/Unit-1_VHA.ipynb 29/29

You might also like