python(2)-条件判断、循环等

1.字符
str=‘sweet’
str.upper() 字符全大写 SWEET
str.title() 字符首字母大写 Sweet
str.lower() 字符全小写 sweet
 
2.if条件判断
(1)if a==b or/and c!=d 方式
(2)if a in/notin list1 方式
举例如下:
banned_users = ['andrew', 'carolina', 'david']user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")
结果:Marie, you can post a response if you wish.
(3)if-elif-else
(4)list=[]列表为空,if list 返回False
 
3.用户输入和while循环
3.1 函数input()的工作原理
函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用
message = input("Tell me something, and I will repeat it back to you: “)
print(message)
结果:
Tell me something, and I will repeat it back to you: Hello everyone! 提示信息后,输入Hello everyone!后,输入存入message
Hello everyone! 打印message的值
 
3.2使用int()来获取数值输入
举例:
age = input("How old are you? “)
How old are you? 21
age = int(age)
age >= 18
True
 
3.3求模运算符 %
求模运算符(%)是一个很有用的工具,将两个数相除并返回余数。
 
3.4while循环
(1)用法举例:
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
 
(2)使用break退出循环
break 立即退出循环,不再执行循环余下的代码。
 
(3)在循环中使用continue
continue 会返回到循环开头,并根据条件测试结果决定是否继续执行循环,不会像break那样直接退出整个循环,只会跳出当前执行的那一条。
 
(4)使用while循环来处理列表和字典
一种办法是使用一个while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中。举例如下:
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace’]
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:(直到这个列表所有值循环玩停止)
    current_user = unconfirmed_users.pop()
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)
 
# 显示所有已验证的用户
print("\nThe following users have been confirmed:”)
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
 
(5)删除包含特定值的所有列元素
举例:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat’]
print(pets)
while 'cat' in pets:
    pets.remove('cat’)
 
(6)使用用户输入来填充字典
举例如下:
responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("\nWhat is your name? “)
    response = input("Which mountain would you like to climb someday? “)
    # 将答卷存储在字典中
    responses[name] = response
    # 看看是否还有人要参与调查
    repeat = input("Would you like to let another person respond? (yes/ no) “)    
    if repeat == 'no’:
        polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results —")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")
结果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
 
What is

猜你喜欢

转载自www.cnblogs.com/Testerblanche/p/9101220.html
今日推荐