Thursday, April 20, 2023

Ch 2 - Operators in Python

Python divides the operators into the following seven groups:

  • Python divides the operators into the following seven groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Arithmetic operators

Floor Division

+ And * Operators Can Act on Strings

String Concatenation using + Operator >>> x = 'johanth' >>> y = 'yada' >>> x + y 'johanthyada' String repetition using * Operator >>> x*3 'johanthjohanthjohanth' This phenomenon is over-loading of operator. >>> a = 5 >>> b = 6 >>> a + b 11 >>> a = "rakesh" >>> b = "vikash" >>> a + b 'rakeshvikash' >>> >>> a = 5 >>> b = 6 >>> a*b 30 >>> a = "rakesh" >>> b = 'vikash' >>> a * 3 'rakeshrakeshrakesh' >>> b * 2 'vikashvikash' >>> >>> l = ['rakesh', 'vikash', 'ashish'] >>> l * 3 ['rakesh', 'vikash', 'ashish', 'rakesh', 'vikash', 'ashish', 'rakesh', 'vikash', 'ashish'] >>>

+ And * Operators Can Act on Lists

>>> l = ['rakesh', 'vikash', 'ashish'] >>> l * 3 ['rakesh', 'vikash', 'ashish', 'rakesh', 'vikash', 'ashish', 'rakesh', 'vikash', 'ashish'] >>> k = ['johanth', 'sonia'] >>> l + k ['rakesh', 'vikash', 'ashish', 'johanth', 'sonia'] >>>

Assignment Operators

Python does not have ++ (as in i++) operator.

If you want to increment a variable:

x += 1

Assignment Operator (Problem)

  • What is the output of this program?
  • x = 5
  • y = 10
  • x = y
  • print(x)
  • print(y)

Assignment Operator (Solution)

  • What is the output of this program?
  • x = 5 # x is the variable name. Explicit value being passed is 5.
  • y = 10 # y is the variable name. Explicit value being passed is 10.
  • x = y # Variable which is taking the value is on the left. X is taking the value. And value being passed is 10 through y.
  • print(x)
  • print(y)
The answer is:
10
10
  

Comparison Operators

Logical Operators

“and” in C++ is: &&

“or” in C++ is: ||

>>> x = 6
>>> y = x < 7
>>> y
True
>>> not y
False
>>> not(y)
False
>>>   

Truth Table For ‘and’

If both expressions are True, then it will return True.
Left Side Exp Right Side Exp Overall Result
True True True
False True False
True False False
False False False

Identity Operators

Membership Operators

>>> l
['rakesh', 'vikash', 'ashish']
>>> 'rakesh' in l
True
>>> 'sonia' in l
False
>>>   

Bitwise Operators

Tags: Python,Technology,

No comments:

Post a Comment