- Hands-On Data Science and Python Machine Learning
- Frank Kane
- 313字
- 2021-07-15 17:15:03
Looping
The last concept I want to cover in our Python basics is looping, and we saw a couple of examples of this already, but let's just do another one:
for x in range(10):
print (x),
The output of the previous code is as follows:
0 1 2 3 4 5 6 7 8 9
For example, we can use this range operator to automatically define a list of numbers in the range. So if we say for x in range(10), range 10 will produce a list of 0 through 9, and by saying for x in that list, we will iterate through every individual entry in that list and print it out. Again, the comma after the print statement says don't give me a new line, just keep on going. So the output of this ends up being all the elements of that list printed next to each other.
To do something a little bit more complicated, we'll do something similar, but this time we'll show how continue and break work. As in other languages, you can actually choose to skip the rest of the processing for a loop iteration, or actually stop the iteration of the loop prematurely:
for x in range(10):
if (x is 1):
continue
if (x > 5):
break
print (x),
The output of the above code is as follows:
0 2 3 4 5
In this example, we'll go through the values 0 through 9, and if we hit on the number 1, we will continue before we print it out. We'll skip the number 1, basically, and if the number is greater than 5, we'll break the loop and stop the processing entirely. The output that we expect is that we will print out the numbers 0 through 5, unless it's 1, in which case, we'll skip number 1, and sure enough, that's what it does.
- C++面向?qū)ο蟪绦蛟O(shè)計(jì)(第三版)
- 國(guó)際大學(xué)生程序設(shè)計(jì)競(jìng)賽中山大學(xué)內(nèi)部選拔真題解(二)
- Objective-C Memory Management Essentials
- PHP 從入門到項(xiàng)目實(shí)踐(超值版)
- Visual Basic程序設(shè)計(jì)習(xí)題解答與上機(jī)指導(dǎo)
- Oracle BAM 11gR1 Handbook
- 數(shù)據(jù)結(jié)構(gòu)(C語言)
- 軟件工程
- 深入理解Android:Wi-Fi、NFC和GPS卷
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- OpenCV 4計(jì)算機(jī)視覺項(xiàng)目實(shí)戰(zhàn)(原書第2版)
- Arduino計(jì)算機(jī)視覺編程
- Maker基地嘉年華:玩轉(zhuǎn)樂動(dòng)魔盒學(xué)Scratch
- Instant Zurb Foundation 4
- 軟件測(cè)試分析與實(shí)踐