Python Decision Making Statements with Syntax

Python Decision Making Statements with Syntax

Before we begin with python decision making expressions, let us revise Python concepts.

Sometimes, in a program, we may want to make a decision based on a condition. We know that an expression’s value can be True or False. We may want to do something only when a certain condition is true. For example, assume variables a and b. If a is greater, then we want to print “a is greater”. Otherwise, we want to print “b is greater”. For this, we use an if-statement. Also, operators come in handy when you want to join conditions to make a composite one.

Let us see at various python decision making expressions in details with syntax and example. So let’s install python on Windows first and revise Python syntax for programming in Python.

if Statements

An if statement in python takes an expression with it. If the expression amounts to True, then the block of statements under it is executed. If it amounts to False, then the block is skipped and control transfers to the statements after the block. But remember to indent the statements in a block equally. This is because we don’t use curly braces to delimit blocks. Also, use a colon(:) after the condition.

Before starting with example, let us see various types of variables and data types in Python as it will help in better programming.

  1. a=7
  2. if a>6:
  3. print(f”{a} is good”)

7 is good

Here, since 7>6, the condition is true. So, it prints the given string.

  1. if 1:
  2. print(“yay”)

yay

We know, 1 has a Boolean value of True. So, the condition is true, and it prints ‘yay’.

  1. if(1==1):
  2. print(“1”)

You can also write the condition in parentheses. It does not cause a syntax error.

if-else Statements

What happens when the condition is untrue? We can mention that it in the block after the else statement. An else statement comes right after the block after ‘if’.

  1. if 2<1:
  2. print(“2”)
  3. else: #This causes a syntax error
  4. if 2<1:
  5. print(“2”)
  6. else:
  7. print(“1”)

Refer Top 10 Python Books to Learn Python Programming

Pay attention to the indent. The else keyword does not appear in the if-block. Press Backspace to undo the automatic indent. Here, 2 is not less than 1. So, the statements in the else-block are executed. It prints 1.

  1. if 2<1:
  2. print(“2”)
  3. else:
  4. print(“1”)
  5. else: #This causes a syntax error

As appears in the above example, you cannot posit two else statements under an if. It causes a syntax error.

Read Complete Article >>

Related Posts

要查看或添加评论,请登录

社区洞察

其他会员也浏览了