Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python Loop sentence

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use Python loop sentences". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. for cycle

The for loop can be used to traverse an object (traversal: to put it colloquially, it is to access the first element of the loop to the last two elements).

1. For recycling scenarios

We want an operation to be repeated and the number of loops known is that we can use for loops

All no loops can be implemented in while.

2. Grammar format

For i in A set of values: # A set of values can be a basic type other than numbers

Actions to be performed

3. An example of for loop operation

The for loop traverses basic types of data other than numbers, such as strings, tuples, lists, collections, dictionaries, files, etc. We can also traverse through a sequential index. The specific actions are as follows:

① for loop traverses strings

# for loop traversing strings

Str='abc'

For i in str:

Print (I)

The results are as follows:

A

B

C

② for loop traversal tuple

Tup1= (31, 29, 31, 30, 31, 31, 31, and 31)

For i in tup1:

Print (iQuery endgame'') # end=' 'does not wrap

The results are as follows:

31 29 31 30 31 30 31 31 30 31 30 31

③ for Loop through the list

Fruits= ['apple','orange','banana','grape']

For fruit in Fruits:

Print (fruit)

The results are as follows:

Apple

Orange

Banana

Grape

④ for Loop traverses the collection

Set1= {'lisi',180,60,99}

For i in set1:

Print (I)

The results are as follows:

Lisi

ninety-nine

one hundred and eighty

sixty

⑤ for Loop traversal Dictionary

Note: the Python dictionary (Dictionary) items () function returns a traverable (key, value) tuple array as a list.

Dict1= {'name':'lisi','height':180,'weight':60,'score':99}

For kjournal v in dict1.items (): # traversing the key-value pairs in the dictionary dict1

Print (kjinghewi->', v)

Print ('-')

For k in dict1.keys (): # iterate through all the keys in the dictionary dict1

Print (k)

Print ('-')

For v in dict1.values (): # iterate through all the values in the dictionary dict1

Print (v)

The results are as follows:

Name-> lisi

Height-> 180

Weight-> 60

Score-> 99

-

Name

Height

Weight

Score

-

Lisi

one hundred and eighty

sixty

ninety-nine

⑥ traversal file

For content in open ("1.txt"): # 1.txt under the current directory

Print (content)

The results are as follows:

Leaving the White Emperor Town at Dawn Leaving at dawn the White Emperor crowned with cloud, I've sailed a thousand miles through canyons in a day.

With monkeys' sad adieus the riverbanks are loud; My skiff has left ten thousand mountains far away.

⑦ for loop to realize 1 to 9 continuous multiplication

Sum = 1

For i in list (range (1M10)): # range sequence contains left but not right

Sum * = I

Print ("1, 2... 9 =", sum)

The results are as follows:

1, 2... 9 = 362880

⑧ in addition to the above, we can also traverse through a sequential index

Usage of range: range (5)-- > 1 parameter, from 0 to 5 does not contain 5 (that is, left but not right); range (5, 15)-- > 2 parameters, from 5 to 15 does not contain 15 position range (5-5)-- > 3 parameters, from 5 to 55 does not contain 55, and the final parameter 5 is the step size.

For the following example, we use the built-in functions len () and range (); function len () to return the length of the list, that is, the number of elements. Range returns a sequence of integers.

Fruits = ['banana','apple','mango','grape']

For index in range (len (fruits)):

Print ('current fruit:', fruits [index])

The results are as follows:

Current fruit: banana

Current fruit: apple

Current fruit: mango

Current fruit: grape

2. While cycle

While loop, as long as the condition is satisfied, it will continue to cycle, and exit the loop when the condition is not satisfied. Where the execution statement can be a single statement or a block of statements; the judgment condition can be any expression, and any non-zero or non-null (null) value is True.

Note: the judgment condition of a while loop is an expression of type boolean!

1. Grammar format

While judgment condition: # expression of boolean type of judgment condition

Execute statement

2. Example of while loop operation:

① finds the sum of even numbers from 1 to 100

Nasty 1

Sum=0

While n

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report