The difference between for else and if else in Python and how to use it

Source: Internet
Author: User
Tags switch case in python

For else >>> to I in range (0,10): if i > 10:break; Else

print "Hello World";         Output: Hello World >>> to I in range (0,10): if i > 5:break; Else:print "Hello World"; No output


-------------------


That is, in a for loop, if you do not exit from any of the break, the else that is corresponding to is executed


If you exit from the break, the else part is not executed.


If Else

The Else statement can be combined with an if statement.

The Else statement is an optional statement that may have only one else statement after the IF.


If expression:
    statement (s)
else:
    statement (s)
elif Statement

The Elif statement allows you to check whether multiple expressions are true and immediately executes the corresponding code block if one of the criteria evaluates to True.

Like the Else statement, the ELIF statement is optional. However, unlike the Else statement, the Else statement can have at most one statement, and there can be any number of elif statements after if.

Grammar

If Expression1:statement (s) elif expression2:statement (s) elif expression3:statement (s) else:statement (s)

Python does not provide switch or case statements like other programming languages, but you can use if. Elif...else statement to simulate a switch case, as follows:

#!/usr/bin/python3

amount = Int (input ("Enter Amount:"))

if amount<1000:
   discount = amount*0.05
   Print ("discount=%f"% (Discount))
elif amount<5000:
   Discount = amount*0.10
   print ("discount=%f"% ( Discount)
else:
   discount = amount*0.15
   print ("discount=%f"% (discount))

print ("Net payable=%f"% ( Amount-discount))
Python

When you execute the above code, the following results are generated-

Enter amount:600
discount=30.0
net payable=570.0

enter amount:3000
discount=300.0
Net payable=2700.0

Enter amount:6000
discount=900.0
Net payable=5100.0






  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.