explain various data types in python with an example
Answers
In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating number or even complex numbers. These values are defined as int , float and complex class in Python. Integers – This value is represented by int class.
Conditional statements
Conditional statements are mostly used to check for validation of a given situation/condition. They deal with Boolean values and according to the result, run the required code.
There are four conditional statements.
If
If - Else
If - Elif
Nested - If
1. If
This statement is used for decision making. It will run the body of the code, if the given 'if' condition is true.
Syntax:
if expression
:
statement
Example:
>>> if 34>7:
print("34 is greater.")
34 is greater. [Output]
Since the given expression was true, it ran the body of the code.
Suppose it wasn't true.
>>> if 4>54:
print("4 is the greater value.")
[No output.]
There was no specific output here as we haven't mentioned what has to be printed if the condition is false.
This is why we have the second type of conditional statement:
2. If - Else
This is also used for decision making. If the 'if' expression results false, it'll run the 'else' part.
Syntax:
if expression
:
statement
else:
statement
Example:
if 51<41:
print("41 is the greater number.")
else:
print("51 is the greater number.")
51 is the greater number. [Output]
Since the 'if' condition was false, the 'else' condition was given as the output.
3. If - Elif
This conditional statement is mainly used for repeated checking or rather as a third possibility if the 'if' and 'else' part is false.
Syntax:
if expression:
statement
elif expression:
statement
else:
statement
Example:
>>> if x>y:
print(x, "is the greater value.")
elif x == y:
print(x, "and", y, "are equivalent values.")
else:
print(y, "is the greater value.")
54 and 54 are equivalent values. [Output]
Since the 'if' and 'else' conditions were false, it ran the 'elif' code.
'Elif' can be used multiple times.
4. Nested - If
Nested - If is when you're using conditional statements inside another one.
Syntax:
if expression:
statement
if expression:
statement
elif expression:
statement
else:
Example:
>>> country == "US"
>>> total = 45
>>> if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
Shipping Cost is $50 [Output]
Here, since the 'if' condition was satisfied, it ran the body of he code, which included a second 'if' condition to check the total amount.