In this post, we will see some basic Python programming constructs.
In Python, we don’t define the data type of the variables. It automatically converts the variable to the type of value assigned to it. For example:
age=25 (integer assignment) age, shoe_size = 25, 8 (multiple integer assignment, age=25 and shoe_size=8) age=25; shoe_size=8 (multiple integer assignment in one line) name = "Ashutosh" (string assignment)
if statement is used to check conditions. If the condition is evaluated to true, the code inside if block will be executed.
if condition: statement1.. statement2.. if(condition): statement
if x > 5: y = 5 z = 6 if(x>5): y=6
if-else statement is used to check conditions for two results. If the condition is evaluated to true, the code inside if block will be executed otherwise the code inside else will be executed.
if condition: statement1.. statement2.. else: statement3.. statement4..
if age >= 18: canVote = True else: canVote = False
if-elif statement is used to check multiple conditions. The code inside the condition that evaluates to true out of multiple conditions will be executed.
if condition: statements.. elif condition: statements.. elif condition: statements.. else: statements
if marks > 90: grade = "A+" elif marks > 80: grade = "A" elif marks > 70: grade = "B+" elif marks > 60: grade = "B" else: grade = "C"
We can write if-else condition in a single line as well.
x = value1 if condition else value2
status = "Can vote" if age >= 18 else "Cannot vote"
Following are the types of operations in Python:
+ Addition 4 + 5 = 9 - Subtraction 6 - 4 = 2 * Multiplication 4 * 3 = 12 / Division 9 / 2 = 4.5 % Modulus 7 % 3 = 1 ** Exponent 2 ** 3 = 8 // Floor Division 9 // 2 = 4
a == b Compare a and b values for equality a > b Check if a is greater than b a >= b Check if a is greater than or equal to b a < b Check if a is less than b a <= b Check if a is less than or equal to b a <> b Check if a is not equal to b
a = b Assign b to a a += b Assign a+b to a a -= b Assign a-b to a a *= b Assign a*b to a a /= b Assign a/b to a a %= b Assign a%b to a a //= b Assign a//b to a
and Checks if both the conditions are true a>5 and b>6 or Checks if one of the conditions are true a>5 or b>6 not Checks if condition is not true not a>5
a & b Bitwise AND a | b Bitwise OR a ^ b Bitwise XOR ~ a Bitwise NOT a << b Bitwise left shift a >> b Bitwise right shift
a in b a is a part of sequence b a not in b a is not part of sequence b
- IdentityChecks if compared objects represents same object or not.
a is b if a and b represents refer to same object a is not b if a and b represents refer to different objects
Operator Precedence specifies which operator should be executed first if there are multiple operators in a single statement.
** ~ + - * / % // + - >> << & ^ | <= < > >= != <> == = %= /= //= **= *= += -= is is not in in not not or and