欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 学习第八天

程序员文章站 2022-07-10 08:20:58
...

(11)if 语句

x = int(input("Please enter an integer: "))
if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')

Please enter an integer: 42
More

(12)for 语句

#Measure some strings
words = ['cat','window','defenestrate']
for w in words:
    print(w,len(w))

cat 3
window 6
defenestrate 12

(13) range()函数

如果你需要遍历一个***,内置函数range()就派上用场了。

for i in range(5):
    print(i)
0
1
2
3
4

# print 5 through 9
for a in range(5,10):
    print(a)
# print 0 3 6 9
for b in range(0,10,3):
    print(b)
# print -10 -40 -70
for c in range(-10,-100,-30):
    print(c)
遍历一个列表,使用range()函数和len()函数。

a = ['Mary','had','a','little','lamb']
for i in range(len(a)):
    print(i,a[i])

0 Mary
1 had
2 a
3 little
4 lamb