Rewrite the following program segment:
Using if else:
String grade = (marks>=90)? "Grade is A" : (marks>=80)? "Grade is B" : "Grade is C";
Answers
Python
Concept
- The questions comes under the topic conditionals expressions.
- An if-elif-else ladder is formed.
- Only one of the the these statements is printed based upon the trueness.
- elif will be considered when the conditions in the if becomes false. For example: marks is 85. In this case , elif will be executed.
- Likewise else is executed in case if and elif both doesn't hold.
Program
marks = int(input("Enter your marks here:\n"))
if (marks >=90):
print("Grade is A.")
elif (marks >=80 and marks < 90):
print("Grade is B.")
else:
print("Grade is C.")
Required program:-
Question:
• Rewrite the following program segment:
Using if else:
String grade = (marks>=90)? "Grade is A" : (marks>=80)? "Grade is B" : "Grade is C";
Answer:
if (marks >= 90)
grade = "A";
else if (marks >= 80)
grade = "B";
else
grade = "C"
Step by step explaination:
If statement is you have seen so far allow you to execute a statement of the condition evaluates to true. For such scenarios, the else-if control is used. The statement that has to be executed when the condition evaluates to false is written under the else-part.
The if-else construct takes the following syntax:
if (condition 1)
statement1;
else
statement2;
Note:
Statement1 is executed when the condition is true.
statement2 is executed when the condition is false.
Know more:
______________________________
In such a ladder, the if statements are executed from the top to bottom as per the following logic:
♦ As soon as one of the conditions becomes true, the statement associated with that if will be executed and the rest of the ladder will be bypassed.
♦ If none of the conditions are true, the final else statement will be executed.
♦ If there is no final else and all the other conditions are false, then no action will take place.
________________________________