首頁 >後端開發 >Python教學 >Day For 迴圈與 If 條件

Day For 迴圈與 If 條件

DDD
DDD原創
2024-11-26 19:16:14413瀏覽

Day  For loop & If condition

for 循環:

Python 中的 for 迴圈用於迭代序列並為該序列中的每個元素執行一段程式碼。

文法:

for variable in sequence:

範例:

txt = '1234'

for num in txt:
    print(num,end=' ')

輸出:

1 2 3 4

如果條件:

if條件是程式設計中的基本控制結構,用於根據給定條件是真還是假做出決策。

文法:

if condition:
    # execute if condition is True
else:
    # execute if condition is False

範例:

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")

輸出:

x is greater than 5

for迴圈與if條件範例:

txt = '12a4'

for num in txt:
    if num>='0' and num<='9':
        print(num,end=' ')
    else:
        print('Not Decimal',end=' ')

輸出:

1 2 Not Decimal 4

程式碼檢查字串 txt 中的每個字元以決定它是否代表數字。如果字元在'0'和'9'之間,則列印;否則,它會列印“Not Decimal”

name = input("Your Name please: ")
print(name)
for alphabet in name:
    print(alphabet, end='*')

Your Name please: pritha
pritha
p*r*i*t*h*a*

練習:

name1 = input("Enter the first name: ")
name2 = input("Enter the second name: ")
name3 = input("Enter the third name: ")
name4 = input("Enter the fourth name: ")
name = [name1, name2, name3, name4]

# Check if names start with 'G'
for letter in name:
    if letter[0]=='G':
        print(letter)
    else:
        continue
# Check if names end with 'a'
for alphabet in name:
    if alphabet[-1]=='a':
        print(alphabet)
    else:
        continue
# Check if names contain a space
for alpha in name:
    for i in alpha:
        if i==' ':
            print(alpha)
        else:
            continue
# Check if names are longer than 9 characters
for character in name:
    if len(character)>9:
        print(character)
    else:
        continue

1.if letter[0] == 'G': 檢查名稱的第一個字元是否為 'G'。
2.if letter[-1] == 'a': 檢查名稱的最後一個字元是否為 'a'。
3.if i == ' ':如果找到空格則印出名稱,然後用break退出內循環。
4.如果len(字元)> 9:檢查名稱長度是否超過9。

Enter the first name:Lakshmi Pritha
Enter the second name:Guru Prasanna
Enter the third name:Guhanraja
Enter the fourth name:Varatharajan
Guru Prasanna
Guhanraja
Lakshmi Pritha
Guru Prasanna
Guhanraja
Lakshmi Pritha
Guru Prasanna
Lakshmi Pritha
Guru Prasanna
Varatharajan










以上是Day For 迴圈與 If 條件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn