Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
427 views
in Python - Control Structures by (54.8k points)
closed by

Explain If and If..else with sample programs?

1 Answer

+1 vote
by (49.1k points)
selected by
 
Best answer

Simple if statement:

Simple if is the simplest of all decision making statements. Condition should be in the form of relational or logical expression.

Syntax:

if :

statements – block 1

In the above syntax if the condition is true statements

– block 1 will be executed.

Example

# Program to check the age and print whether eligible for voting

x = int (input (“Enter your age :”))

if x > = 18:

print (“You are eligible for voting”)

Output 1:

Enter your age: 34 You are eligible for voting 

Output 2:

Enter your age: 16

>>>

As you can see in the second execution no output will be printed, only the Python prompt will be displayed because the program does not check the alternative process when the condition is failed.

if..else statement:

The if., else statement provides control to check the true block as well as the false block. Following is the syntax of ‘if.else’ statement.

Syntax:

if:

statements – block 1

else:

statements – block 2

if..else statement thus provides two possibilities and the condition determines which BLOCK is to be executed.

Example: #Program to check if the accepted number odd or even

a = int(input(“Enter any number :”)) if a%2==0: 

print (a, ” is an even number”)

else:

print (a, ” is an odd number”)

Output 1:

Enter any number: 56 56 is an even number 

Output 2:

Enter any number: 67 67 is an odd number An alternate method to rewrite the above program is also available in Python. The complete if.else can also written as:

Syntax:

variable = variable 1 if condition else variable 2

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

...