一个专注于计算机编程和硬件学习的博客主
27/1
2019

Python--控制流

控制流

if语句

  • if 判断条件:
game = 1000
money = 100000
if game<2000:
    game+=1000
    money-=1000
print('You have '+str(game)+'RMB in your game,'
      + 'you have '+str(money)+'RMB in your money!')
You have 2000RMB in your game,you have 99000RMB in your money!

  • if 、else 、elif
people='Tom'
if people=='Mary':
    print('Hello Mary!')
elif people=='Tom':
    print('Hello,Tom~')
else:
    print('Go away~')
Hello,Tom~

for循环

names = ['Tom', 'mary', 'jimmy', 'William']
New_names = []
for name in names:
    New_names.append(name.title())
print(New_names)
['Tom', 'Mary', 'Jimmy', 'William']

  • range(star,stop,step)for结合进行循环

    • star 开始数值,不填为0
    • stop 结束数值,需要填
    • step 间隔数值,不填为1
for i in range(1, 5, 2):
    print(i)
1
3

while循环

  • while
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9]
equipped = []
while sum(equipped) <= 20:
    print(equipped)
    equipped.append(deck.pop())
print(equipped)
[9]
[9, 8]
[9, 8, 7]

  • whilebreak
while True:
    word=input('Enter string to capitalize[type q to quit]:')
    if word == 'q':
        break
    print(word.capitalize())
Enter string to capitalize[type q to quit]:hello
Hello
Enter string to capitalize[type q to quit]:q
 

  • while与continue
while True:
    value = input('Even number please~[enter q to quit]:')
    if value == 'q':
        break
    number = int(value)
    if number % 2 == 0:
        continue
    print('I said even number,are you blind?')
Even number please~[enter q to quit]:2
Even number please~[enter q to quit]:6
Even number please~[enter q to quit]:8
Even number please~[enter q to quit]:5
I said even number,are you blind?
Even number please~[enter q to quit]:q
 

添加新评论