Introduction to Conditional Statements
Introduction to Conditional Statements
Fundamentals of Comparisons
Introduction
We have been introduced to numeric values and strings. Another category of value is a type of value that can be said to be true or to be false. Such a value is referred to as Boolean.
A comparison is a Boolean operation that finds out the relationship between two values. The operation produces a result of True or False. The comparison is performed between two values.
To perform comparisons and validations on values, you use some symbols referred to as Boolean operators. The operator can be included between two operands as in:
operand1 operator operand2
This is referred to as a Boolean expression.
Practical Learning: Introducing Comparisons
print() print("Watts' A Loan") print("============================================") interest_rate : float = 16.75 # % periods : int = 40 # months print("Enter the information to set up the loan") print("Loans Types") print('1. Personal Loan') print('2. Car Financing') print('3. Musical Instrument') print('4. Furniture Purchase') print('5. Boat Financing') print('0. Other') print('--------------------------------------------') category = input("Enter type of loan (1-4): ") loan_amount = float(input("Loan Amount: ")) iRate : float = interest_rate / 100.00 years : float = periods / 12 interest_amount : float = loan_amount * iRate * years future_value : float = loan_amount + interest_amount print("============================================") print("\tWatts' A Loan") print('--------------------------------------------') print(f"Loan Type: {category}") print(f"Loan Amount: {loan_amount}") print(f"Interest Rate: {interest_rate:.2f}%") print(f"Periods: {periods} Months") print('-------------------------------------------') print(f"Interest Amount: {interest_amount:.2f}") print(f"Future Value: {future_value:.2f}") print("===========================================")
Watts' A Loan ============================================ Enter the information to set up the loan Loans Types 1. Personal Loan 2. Car Financing 3. Musical Instrument 4. Furniture Purchase 5. Boat Financing 0. Other -------------------------------------------- Enter type of loan (1-4): 1 Loan Amount: 1750 ============================================ Watts' A Loan -------------------------------------------- Loan Type: 1 Loan Amount: 1750.0 Interest Rate: 16.75% Periods: 40 Months ------------------------------------------- Interest Amount: 977.08 Future Value: 2727.08 =========================================== Press any key to continue . . .
if an Operand is Operating on a Value
A conditional statement is a logical expression that produces a True or False result. You can then use that result as you want. To create a logical expression, you use a Boolean operator. To perform this operation, you can use an operator named if. The formula to follow is:
if condition: statement
If you are using Microsoft Visual Studio, to create an if conditional statement, right-click the section where you want to add the code and click Snippet... Double-click Insert Snippet. Double-click Python. In the list of options, click if.
In our formula of the if conditional statement, the condition can be a type of Boolean expression. The condition can have the following formula:
operand1 Boolean-operator operand2
Any of the operands can be a constant or the name of a variable. The whole expression is the condition. The condition is followed by a required colon (:). If the expression produces a True result, then the statement would execute.
The section on the line after the colon is the body of the conditional statement. That section must be indented. That section can contain one or more lines of code.
To find out whether two things are equal, use an operator represented as ==. The formula to use it is:
value1 == Value2
The equality operation is used to find out whether two variables, or one variable and a value (a constant) hold the same value. The operation can be illustrated as follows:
It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first is used to give a new value to a variable, as in Number = 244. The operand on the left side of = must always be a variable and never a constant. The == operator is never used to assign a value; this would cause an error. The == operator is used only to compare two values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. Here is an example:
if answer == 1:
print("You answered '1'")
The body of a conditional statement can contain more than one line of code. Here is an example:
if answer == 1:
print("You answered '1'.")
print("You may be tempted to answer 'Noooooooooo'.")
print("But next time, answer 'Yes'.")
Introduction
A Boolean value is a value that is stated as True or False. To store a Boolean value in the computer memory, declare a variable using a regular name of a variable. If you want a Boolean variable to hold a starting value, assign it a value of True or False. Here is an example:
drinking_under_age = False
A Boolean variable can also be initialized with a Boolean expression. Here is an example:
employee_is_full_time = position == "Manager"
To make your code easy to read, you should include the logical expression in parentheses. This can be done as follows:
employee_is_full_time = (position == "Manager");
A Boolean Type
A Boolean variable is supported through a data type named bool. Therefore, if you want, when declaring a variable for a Boolean data type, you can apply this data type to it. Here is an example:
drinking_under_age : bool = False
Introduction to Processing Boolean Values
In the previous lessons, we saw how to display the values of variables that hold numeric values or strings. In the same way, if you declare and initialize a Boolean variable, to display it to a console, you can write the Boolean value, the Boolean variable, or a Boolean expression, in the parentheses of print(). Here is an example:
drinking_under_age = False print("Drinking Under Age:") print(drinking_under_age) print("==================================")
This would produce:
Drinking Under Age: False ================================== Press any key to continue . . .
We also learned to combine a message and the variable on the same line. You can also do that with a Boolean variable. Here is an example:
drinking_under_age = False print("Drinking Under Age:", drinking_under_age) print("==================================")
If a variable was initialized with a Boolean expression, you can write that variable in the parentheses of print() and it would display the value of the variable. Here is an example:
position = "Manager" employment_status = (position == "Contractor") print("The worker is a contractor:", employment_status) print("==================================")
This would produce:
The worker is a contractor: False ================================== Press any key to continue . . .
In the above example, we used an expression that uses the == operator. In the same way, you can create an expression that uses any of the other Boolean operators.
Updating a Boolean Variable
As seen with other variables, after declaring, initializing, and using a Boolean variable, at one time, you may need to change its value. This is referred to as updating a variable.
Getting a Boolean Value
Getting the value of a Boolean variable depends on the type of application. As seen in the previously lesson, you can request any type of value, such as a number or a string, then perform a comparison to judge whether that value responds to some criterion you wanted. Here is an example:
answer = input("Did you drink before leaving the party (y/n)? ") if answer == 'y': print("Driving while intoxicated:", answer) print('--------------------------------------------------------') response = input("Did you drink before leaving the party (0=No/1=Yes)? ") if response == '0': print("Driving while intoxicated:", response) print("=======================================================")
Primary Topics on Conditional Statements
if a Condition is True/False
One way to formulate a conditional statement is to find out whether a situation is true or false. In this case, one of the operands must be a Boolean value as True or False. The other operand can be a Boolean variable. Here is an example:
employee_is_full_time = False
if False == employee_is_full_time:
print("The worker is not a full-time employee")
print("======================================")
This would produce:
The worker is not a full-time employee ====================================== Press any key to continue . . .
One of the operands can also be an expression that holds a Boolean value.
Imagine that you want to evaluate the condition as true. Here is an example:
employee_is_full_time = True
if employee_is_full_time == True:
print("The worker is a full-time employee")
print("======================================")
This would produce:
The worker is a full-time employee ====================================== Press any key to continue . . .
If a Boolean variable (currently) holds a true value (at the time you are trying to access it), when you are evaluating the expression as being True, you can omit the == True or the True == expression in your statement. Therefore, the above expression can be written as follows:
employee_is_full_time = True
if employee_is_full_time:
print("The worker is a full-time employee")
print("======================================")
Creating Multiple Conditions
Just as you can create one if condition, you can write more than one to consider different outcomes of an expression or an object. Here are examples
answer = input("Enter your employment status (f for full-time, p for part-time): ") print("--------------------------------------------------------------------") if answer == "f": print("The worker is a full-time employee.") print("====================================================================") if answer == "p": print("The employee works part-time.") print("====================================================================") if answer == "F": print("The employee has a full-time status.") print("====================================================================") if answer == "P": print("The employee performs as a part-time worker.") print("====================================================================")
Practical Learning: Comparing for Equality
print("Watts' A Loan")
print("============================================")
interest_rate : float = 16.75 # %
periods : int = 40 # months
loan_name : str = "Other"
print("Enter the information to set up the loan")
print("Loans Types")
print('1. Personal Loan')
print('2. Car Financing')
print('3. Musical Instrument')
print('4. Furniture Purchase')
print('5. Boat Financing')
print('0. Other')
print('--------------------------------------------')
category = input("Enter type of loan (1-4): ")
loan_amount = float(input("Loan Amount: "))
if (category == "1"):
periods = 24
interest_rate = 18.65
loan_name = 'Personal Loan'
if (category == "2"):
periods = 60
interest_rate = 5.55
loan_name = 'Car Financing'
if (category == "3"):
periods = 36
interest_rate = 14.5
loan_name = 'Musical Instrument'
if (category == "4"):
periods = 48
interest_rate = 22.25
loan_name = 'Furniture Purchase'
if (category == "5"):
periods = 72
interest_rate = 3.5
loan_name = 'Boat Financing'
iRate : float = interest_rate / 100.00
years : float = periods / 12
interest_amount : float = loan_amount * iRate * years
future_value : float = loan_amount + interest_amount
print("============================================")
print("\tWatts' A Loan")
print('--------------------------------------------')
print(f"Loan Type: {loan_name}")
print(f"Loan Amount: {loan_amount}")
print(f"Interest Rate: {interest_rate:.2f}%")
print(f"Periods: {periods} Months")
print('-------------------------------------------')
print(f"Interest Amount: {interest_amount:.2f}")
print(f"Future Value: {future_value:.2f}")
print("===========================================")
Watts' A Loan ============================================ Enter the information to set up the loan Loans Types 1. Personal Loan 2. Car Financing 3. Musical Instrument 4. Furniture Purchase 5. Boat Financing 0. Other -------------------------------------------- Enter type of loan (1-4): 2 Loan Amount: 26885 ============================================ Watts' A Loan -------------------------------------------- Loan Type: Car Financing Loan Amount: 26885.0 Interest Rate: 5.55% Periods: 60 Months ------------------------------------------- Interest Amount: 7460.59 Future Value: 34345.59 =========================================== Press any key to continue . . .
|
|||
Previous | Copyright © 2021-2024, FunctionX | Thursday 30 December 2021 | Next |
|