python基础3
文章目录
用户输入和while
# input 输入 字符串
name=input("please enter your name: ")
print("welcome " + name)
age=input("age== ")
print(age) #字符串类型
age=int(age) #int()类型转换
print(age)
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
## break
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
# 不小心进入无线循环时, ctrl+c
#创建一个存储外星人的空列表
aliens2=[]
#创建30个外星人 range(0,30)
for alien_number in range(0,30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens2.append(new_alien)
#修改前三个信息
for alien in aliens2[0:3]:
if alien['color']=='green':
alien['color']='yellow'
alien['speed']='fast'
alien['points'] = 10
for alien in aliens2[0:5]:
print(alien)
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city=input(prompt)
if city=='quit':
break
else:
print("I'd love to go to " + city.title() + "!")
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) jinan
I'd love to go to Jinan!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) shandong
I'd love to go to Shandong!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
#### 7.3 使用while循环处理列表和字典
unconfirmed_users=['a','b','c']
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop() #删除最后一个元素
print("Verifying user:"+ current_user.title())
confirmed_users.append(current_user)
#显示所有已验证的用户
print("\nThe users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
Verifying user:C
Verifying user:B
Verifying user:A
The users have been confirmed:
C
B
A
#删除指定值得列表元素
pets=['dog','cat','rabbit','dog','cat','goldfish']
print(pets)
while 'dog' in pets:
pets.remove('dog')
print(pets)
['dog', 'cat', 'rabbit', 'dog', 'cat', 'goldfish']
['cat', 'rabbit', 'cat', 'goldfish']
#用户输入填充字典
user_infos={}
active=True
while active:
name=input("enter name: ")
age=input("enter age:")
user_infos[name]=age
repeat=input("Repeat? yes/no:")
if repeat == 'no':
active=False
print("User information: ")
for name,age in user_infos.items():
print(name + " "+ age)
enter name: abc
enter age:18
Repeat? yes/no:yes
enter name: def
enter age:21
Repeat? yes/no:no
User information:
abc 18
def 21