国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
01 A for loop using tryexcept
02 Exponential Operations
03 Nested Loops
04 Use the split() function in a for loop
1. Use the split() function for word comparison
2. 使用split()函數(shù)打印指定格式的文本
3. 使用split()函數(shù)打印固定寬度的文本
4. 使用split()函數(shù)比較文本字符串
05 用基礎(chǔ)的for循環(huán)顯示字符串中的字符
06 join()函數(shù)
Home Backend Development Python Tutorial 6 examples, 8 code snippets, detailed explanation of For loop in Python

6 examples, 8 code snippets, detailed explanation of For loop in Python

Apr 11, 2023 pm 07:43 PM
python for cycle

Python supports for loops, and its syntax is slightly different from other languages ??(such as JavaScript or Java). The following code block demonstrates how to use a for loop in Python to iterate over the elements in a list:

The above code snippet separates three letters into rows Printed. You can limit the output to the same line by adding a comma "," after the print statement (if you specify a lot of characters to print, it will "wrap"), the code is as follows:

When you want to display the content in the text in one line instead of multiple lines, you can use the above form of code. Python also provides the built-in function reversed(), which can reverse the direction of the loop, for example:

Note that only when the size of the object is determined , or the reverse traversal function is only effective when the object implements the _reversed_() method.

01 A for loop using tryexcept

Listing 1's StringToNums.py illustrates how to sum a set of integers converted from strings.

  • Listing 1 StringToNums.py
<ol><pre class='brush:php;toolbar:false;'>line = '1 2 3 4 10e abc' 
sum  = 0 
invalidStr = "" 
print('String of numbers:',line) 
for str in line.split(" "): 
  try: 
    sum = sum + eval(str) 
  except: 
    invalidStr = invalidStr + str + ' ' 
print('sum:', sum) 
if(invalidStr != ""): 
  print('Invalid strings:',invalidStr) 
else: 
  print('All substrings are valid numbers') 

Listing 1 first initializes the variables line, sum and invalidStr, and then displays the content of line. Next, the content in the line is divided into words, and then the values ??of the words are accumulated into the variable sum one by one through the try code block. If an exception occurs, the contents of the current str are appended to the variable invalidStr.

When the loop execution ends, Listing 1 prints out the sum of the numeric words, and displays the non-numeric words after it. Its output looks like this:

02 Exponential Operations

Nth_exponet.py in Listing 2 illustrates how to calculate a set of integers of power.

  • Listing 2 Nth_exponet.py
<ol ><pre class='brush:php;toolbar:false;'>maxPower = 4 
maxCount = 4 
def pwr(num): 
  prod = 1 
  for n in range(1,maxPower+1): 
    prod = prod*num 
    print(num,'to the power',n, 'equals',prod) 
  print('-----------') 
for num in range(1,maxCount+1): 
    pwr(num) 

There is a pwr() function in Listing 2, whose parameter is a numeric value. The loop in this function can print out the parameter raised to the power 1 to n, with n ranging from 1 to maxCount 1.

The second part of the code calls the pwr() function from 1 to maxCount 1 through a for loop. Its output looks like this:

03 Nested Loops

Listing 3 of Triangular1.py illustrates how to print a line Consecutive integers (starting at 1) where the length of each line is 1 greater than the previous line.

  • Listing 3 Triangular1.py
<ol ><pre class='brush:php;toolbar:false;'>max = 8 
for x in range(1,max+1): 
  for y in range(1,x+1): 
    print(y,'', end='') 
  print()  

Listing 3 first initializes the max variable to 8, and then executes a loop through the variable x from 1 to max 1 . The inner loop has a loop variable y with a value from 1 to x 1, and prints the value of y. Its output is as follows:

04 Use the split() function in a for loop

Python supports various convenient String operation related functions, including split() function and join() function. The split() function is useful when you need to tokenize (i.e., "split") a line of text into words and then use a for loop to iterate through the words.

The join() function is the opposite of the split() function, which "joins" two or more words into one line. You can easily remove extra spaces in a sentence by using the split() function and then calling the join() function so that there is only one space between each word in the text line.

1. Use the split() function for word comparison

Compare2.py in Listing 4 illustrates how to compare each word in a text string with another word using the split() function Compare.

  • Listing 4 Compare2.py
<ol ><pre class='brush:php;toolbar:false;'>x = 'This is a string that contains abc and Abc' 
y = 'abc' 
identical = 0 
casematch = 0 
for w in x.split(): 
  if(w == y): 
    identical = identical + 1 
  elif (w.lower() == y.lower()): 
    casematch = casematch + 1 
if(identical > 0): 
 print('found identical matches:', identical) 
if(casematch > 0): 
 print('found case matches:', casematch) 
if(casematch == 0 and identical == 0): 
 print('no matches found') 

Listing 4 uses the split() function to compare each word in the string x with the word abc Compare. If the words match exactly, the identical variable is incremented by 1; otherwise, a case-insensitive comparison is attempted, and if there is a match, the casematch variable is incremented.

The output of Listing 4 is as follows:

2. 使用split()函數(shù)打印指定格式的文本

清單5 的FixedColumnCount1.py 說明了如何打印一組設(shè)定固定寬度的字符串。

  • 清單5 FixedColumnCount1.py
<ol ><pre class='brush:php;toolbar:false;'>import string 
wordCount = 0 
str1 = 'this is a string with a set of words in it' 
print('Left-justified strings:') 
print('-----------------------') 
for w in str1.split(): 
   print('%-10s' % w) 
   wordCount = wordCount + 1 
   if(wordCount % 2 == 0): 
      print("") 
print("n") 
print('Right-justified strings:')  
print('------------------------')  
wordCount = 0 
for w in str1.split(): 
   print('%10s' % w) 
   wordCount = wordCount + 1 
   if(wordCount % 2 == 0): 
      print() 

清單5 首先初始化變量wordCount和str1,然后執(zhí)行兩個(gè)for循環(huán)。第一個(gè)for循環(huán)對(duì)str1的每個(gè)單詞進(jìn)行左對(duì)齊打印,第二個(gè)for循環(huán)對(duì)str1的每個(gè)單詞進(jìn)行右對(duì)齊打印。在每個(gè)循環(huán)中當(dāng)wordCount是偶數(shù)的時(shí)候就輸出一次換行,這樣每打印兩個(gè)連續(xù)的單詞之后就換行。清單5的輸出如下所示:

3. 使用split()函數(shù)打印固定寬度的文本

清單6 的FixedColumnWidth1.py說明了如何打印固定寬度的文本。

  • 清單6 FixedColumnWidth1.py
<ol ><pre class='brush:php;toolbar:false;'>import string 
left = 0 
right = 0 
columnWidth = 8 
str1 = 'this is a string with a set of words in it and it will be split into a fixed column width' 
strLen = len(str1) 
print('Left-justified column:')  
print('----------------------')  
rowCount = int(strLen/columnWidth) 
for i in range(0,rowCount): 
   left  = i*columnWidth 
   right = (i+1)*columnWidth-1 
   word  = str1[left:right] 
   print("%-10s" % word) 
# check for a 'partial row' 
if(rowCount*columnWidth < strLen): 
   left  = rowCount*columnWidth-1; 
   right = strLen 
   word  = str1[left:right] 
   print("%-10s" % word) 

清單6初始化整型變量columnWidth和字符串類型變量str1。變量strLen是str1的長(zhǎng)度,變量rowCount是strLen除以columnWidth的值。之后通過循環(huán)打印rowCount行,每行包含columnWidth個(gè)字符。代碼的最后部分輸出所有“剩余”的字符。清單6的輸出如下所示:

4. 使用split()函數(shù)比較文本字符串

清單7 的CompareStrings1.py說明了如何判斷一個(gè)文本字符串中的單詞是否出現(xiàn)在另一個(gè)文本字符串中。

  • 清單7 CompareStrings1.py
<ol ><pre class='brush:php;toolbar:false;'>text1 = 'a b c d' 
text2 = 'a b c e d' 
if(text2.find(text1) >= 0): 
  print('text1 is a substring of text2') 
else: 
  print('text1 is not a substring of text2') 
subStr = True 
for w in text1.split(): 
  if(text2.find(w) == -1): 
    subStr = False 
    break 
if(subStr == True): 
  print('Every word in text1 is a word in text2') 
else: 
  print('Not every word in text1 is a word in text2') 

清單7 首先初始化兩個(gè)字符串變量text1和text2,然后通過條件邏輯判斷字符串text2是否包含了text1(并輸出相應(yīng)打印信息)。

清單7的后半部分通過一個(gè)循環(huán)遍歷字符串text1中的每個(gè)單詞,并判斷其是否出現(xiàn)在text2中。如果發(fā)現(xiàn)有匹配失敗的情況,就設(shè)置變量subStr為False,并通過break語句跳出循環(huán),提前終止for循環(huán)的執(zhí)行。最后根據(jù)變量subStr的值打印對(duì)應(yīng)的信息。清單7的輸出如下所示:

05 用基礎(chǔ)的for循環(huán)顯示字符串中的字符

清單8 的StringChars1.py說明了如何打印一個(gè)文本字符串中的字符。

  • 清單8 StringChars1.py
<ol ><pre class='brush:php;toolbar:false;'>text = 'abcdef' 
for ch in text: 
   print('char:',ch,'ord value:',ord(ch)) 
print 

清單8 的代碼簡(jiǎn)單直接地通過一個(gè)for循環(huán)遍歷字符串text并打印它的每個(gè)字符以及字符的ord值(ASCII 碼)。清單8 的輸出如下所示:

06 join()函數(shù)

另一個(gè)去掉多余空格的方法是使用join()函數(shù),代碼示例如下所示:

split()函數(shù)將一個(gè)文本字符串“分割”為一系列的單詞,同時(shí)去掉多余的空格。接下來join()函數(shù)使用一個(gè)空格作為分隔符將字符串text1中的單詞連接在一起。上述代碼的最后部分使用字符串XYZ替換空格作為分隔符,執(zhí)行相同的連接操作。上述代碼的輸出如下:

關(guān)于作者:奧斯瓦爾德·坎佩薩托(OswaldCampesato),專門研究深度學(xué)習(xí)、Java、Android和TensorFlow。他是25本書的作者/合著者。

本文摘編自《機(jī)器學(xué)習(xí)入門:Python語言實(shí)現(xiàn)》,經(jīng)出版方授權(quán)發(fā)布。(ISBN:9787111695240)

?

The above is the detailed content of 6 examples, 8 code snippets, detailed explanation of For loop in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python pandas melt example python pandas melt example Jul 27, 2025 am 02:48 AM

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

python django forms example python django forms example Jul 27, 2025 am 02:50 AM

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

See all articles