Python programming myths that must be understood

Source: Internet
Author: User
Tags range in python

For the python question this afternoon, simply summarize.

Several for nested loops written to themselves, adding if and else always have no results. The reason is that in Python, the For statement is also supported for else. When if else. What was the situation like when they all appeared? As a small example:

     For a in range (4):
	for B in range (4):
		if b >=2:
			print ' b=> ', b
		else:
			print ' a+b=> ', A+b
	If a<=2:
		print ' a,b=> ', a,b
	else:
		print ' a,b,b,a=> ', a,b,b,a

Our intention is: first internal for loop, for b ..., and then execute if a<=3 ... the following statement: Execution result:

a+b=> 0
a+b=> 1
b=> 2
b=> 3
a,b=> 0 3
a+b=> 1
a+b=> 2
b=> 2< C19/>b=> 3
a,b=> 1 3
a+b=> 2
a+b=> 3
b=> 2
b=> 3
a,b=> 2 3
a+b= > 3
a+b=> 4
b=> 2
b=> 3
a,b,b,a=> 3 3 3 3

From the end result, we can get that the last else statement belongs to the For statement. (the statement that belongs to the first occurrence)

Related Article

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.