首页 >后端开发 >Python教程 >Day For 循环和 If 条件

Day For 循环和 If 条件

DDD
DDD原创
2024-11-26 19:16:14465浏览

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