官术网_书友最值得收藏!

The while loop

Remember that when we discussed lists in the first chapter of the book, we mentioned that lists can actually hold heterogeneous data types in Python. A list may contain integers, strings, dictionaries, tuples, or even nested lists. This feature makes lists very powerful and exceptionally easy and intuitive to use. Let's take a look at the following example:

my_list=[1,"a",[1,2,3],{"k1":"v1"}]
my_list[0] -> 1
my_List[1] -> "a"
my_list[2] -> [1,2,3]
my_list[2][0] -> 1
my_list[2][2] -> 3
my_list[3] -> {"k1":"v1"}
my_list[3]["k1"] -> "v1"
my_list[3].get("k1") -> "v1

Let's take a closer look at while loops with the help of the following code, which we will call while_loops.py. We will also see how we can iterate over lists using while loops:

The first portion of the code, lines 2 to 6, depicts a simple usage of the while loop, where we are printing a statement five times. Note that the condition that is specified for the loop to be executed can be placed with or without braces, as shown from lines 7 to 10.

In line 12, we declared a list containing numbers, strings, a float, and a nested list as well. Then, in the final while loop starting at line 14, we iterate over the elements of the list by setting the loop control variable to be less than the length of the list. Within the loop, we check for the type of the list variable. The if type (1) returns an integer class, type (a) returns a string class, and type ([]) returns a list class. When the type is a list, we iterate over its elements again in a nested while loop, and print each one, as shown from lines 19 to 24:

主站蜘蛛池模板: 崇义县| 英吉沙县| 陇西县| 安义县| 乌兰察布市| 鄂伦春自治旗| 普洱| 合肥市| 北川| 瓦房店市| 康马县| 黄大仙区| 乳源| 双柏县| 富平县| 呼图壁县| 林西县| 灵山县| 汉中市| 璧山县| 大英县| 金湖县| 芒康县| 东方市| 古浪县| 达拉特旗| 贵德县| 庆城县| 孝昌县| 西乌珠穆沁旗| 中卫市| 孙吴县| 普兰县| 古交市| 朔州市| 准格尔旗| 宜黄县| 邵阳市| 贺州市| 鄂州市| 武陟县|