python基础练习之实战

#确定列表长度
cars=[‘bow’,‘audi’,‘toyota’,‘subaru’]
long=len(cars) #使用len()快速获悉列表长度
print(long)
for car in cars: #利用for循环遍历整个列表
print(car)
#遍历列表
magicians=[‘alice’,‘david’,‘carolina’]
for magician in magicians:
#print(magician)
print(magician.title() + ‘,that was a great trick’)
print(‘I can not wait to see your next trick,’+magician.title()+’.\n’)
print(‘Thank you,everyone.That was a great magic show’)
#使用range()创建数字列表
numbers=list(range(1,6)) #使用函数list()可将range()的结果转换成列表
print(numbers)
#打印1-10内的偶数
even_numbers=list(range(2,11,2)) #使用range()可以指定步长(步长为2)
print(even_numbers)

squares=[] #空列表
for value in range(1,11):
square=value2
squares.append(square)
print(squares)
#对数字列表进行统计
#digits=[1,2,3,4,5,6,7,8,9,0]
#Min=min(digits)
#print(Min)
#Max=max(digits)
#print(Max)
#Sum=sum(digits)
#print(Sum)
squares=[value
2 for value in range(1,11)] #将前10个数进行平方和(2)
print(squares)
#打印数字1-20
for value in range(1,20):
print(value)
#numbers=list(range(1,1000000))
#for value in range(1,1000000):
#print(value)
#指定索引
players=[‘charles’,‘martina’,‘michael’,‘florence’,‘eli’]
print(players[0:3])
print(players[1:4])
print(players[:4])
print(‘here are the first three players on my team:’)
for player in players[ :3]:
print(player.title())
#复制列表
my_foods=[‘pizza’,‘falafel’,‘carrot cake’]
friend_foods=my_foods[:]
print(‘my favorite foods are:’)
print(my_foods)
print(’\nmy friend favorite foods are:’)
print(friend_foods)
#复制列表 添加一种食品 方法append()列表末尾添加
my_foods=[‘a’,‘b’,‘c’]
friend_foods=my_foods[:]
my_foods.append(‘D’)
friend_foods.append(‘F’)
print(‘my favorite foods are:’)
print(my_foods)
print(’\nmy friend favorite foods are:’)
print(friend_foods)
dimensions=(200,50) #定义元组
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions: #遍历元组dimension
print(dimension)
#修改元组变量
dimensions=(200,50)
print(‘original dimensions:’)
for dimension in dimensions:
print(dimension)
dimensions=(400,60)
print(’\nmodified dimensions:’)
for dimension in dimensions:
print(dimension)
#if语句
cars=[‘ah’,‘bh’,‘ch’]
for car in cars:
if car==‘ah’:
print(car.upper())
else :
print(car.title())
#检查是否相等
requested_topping=‘b’
if requested_topping!=‘c’:
print(‘hold the c!’)
age=19
if age>=18:
print(‘you are old enough to vote!’)
print(‘have you registered to vote yet?’)
age=17
if age>=18:
print(‘you are old enough to vote’)
print(‘have you registed to vote yet?’)
else :
print(‘sorry,you are too young to vote ‘)
print(‘please regist to vote as soon as you turn 18!’)
#检查特殊元素
requested_toppings=[‘mushrooms’,‘green peppers’,‘extra cheese’]
for requested_topping in requested_toppings:
if requested_topping==‘green peppers’:
print(‘sorry,we are out of green peppers right now’)
else:
print(‘adding ‘+requested_topping+’.’)
print(’\nfinished making your pizza’)
#使用多个列表
available_toppings=[‘mushrooms’,‘olive’,‘green peppers’,‘pepperoni’,‘pineapple’,‘extra cheese’]
requested_toppings=[‘mushrooms’,‘french fries’,‘extra cheese’]
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(‘adding ‘+requested_topping+’.’)
else:
print(‘sorry,we do not have’+requested_topping+’.’)
print(’\nfinished making your pizza’)
#访问字典中的值
alien_0 = {‘color’:‘green’,‘points’:5}
print(alien_0[‘color’])
print(alien_0[‘points’])
alien_0 = {‘color’:‘green’,‘points’:5}
new_points = alien_0[‘points’]
print('you just earned ‘+ str(new_points) + ’ points!’)#将整数转换成字符串str()
#添加键-值对
alien_0 = {‘color’:‘green’,‘points’:5}
print(alien_0)
alien_0[‘x_position’] = 0
alien_0[‘y_position’] = 25
print(alien_0)
#先创建一个空字典
alien_0 = {}
alien_0[‘color’] = ‘green’
alien_0[‘points’] = 5
print(alien_0)
#修改字典中的值
alien_0 = {‘color’:‘green’}
print('the alien is ’ + alien_0[‘color’] + ‘.’)
alien_0[‘color’] = ‘yellow’
print(‘the alien now is ’ + alien_0[‘color’] + ‘.’)
#例题:对一个能够以不同速度移动的外星人的位置进行跟踪
alien_0 = {‘x_position’:0,‘y_position’:25,‘speed’:‘medium’}
print(‘original x_position:’ + str(alien_0[‘x_position’]))
if alien_0[‘speed’] == ‘slow’:
x_increment = 1
elif alien_0[‘speed’] == ‘medium’:
x_increment = 2
else :
x_increment = 3
alien_0 [‘x_position’]= alien_0[‘x_position’] + x_increment
print(‘new x_position:’ + str(alien_0[‘x_position’]))
#删除键值对(用del)删除的键值对永远消失
alien_0 = {‘color’:‘green’,‘points’:5}
print(alien_0)
del alien_0[‘points’]
print(alien_0)
#遍历所有的键值对
user_0 = {
‘username’:‘efermi’,
‘first’:‘enrico’,
‘last’:‘fermi’,
}
for key,value in user_0.items():
print(’\nkey: ’ + key)
print('value: ’ + value)
#遍历字典中的键(遍历字典时会默认所有的键)eg:for name in favorite_languages.keys()与for name in favorite_languages一样
favorite_languages = {
‘jen’:‘python’,
‘sarah’:‘c’,
‘edward’:‘ruby’,
‘phil’:‘python’
}
friends = [‘phil’,‘sarah’]
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print('Hi ’ + name.title() +
',I see your favorite_languages is ’ +
favorite_languages[name].title() + ‘!’)#书90页有错误
#第七章 用户输入和while循环
#函数input()让程序暂停运行,等待用户输入一些文本。
message = input('tell me something,and I will repeat it back to you: ')
print(message)
#greater.py
name = input(‘please enter your name: ‘)
print(‘hello,’ + name + ‘!’)
#判断奇数、偶数(用求模运算符%)
number = input(‘Enter a number,I will tell you if it is even or odd: ‘)
number = int(number)
if number%2 == 0:
print(’\nThe number ’ + str(number) + ’ is even.’)
else:
print(’\nThe number ’ + str(number) + ’ is odd.’)
#while循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
#用户退出

prompt = ‘Tell me something,and I will repeat it back to you: ’
prompt += "\nEnter ‘quit’ to end the program. "
message = ‘’
while message != ‘quit’:
message = input(prompt)
print(message)
#用户退出时不打印quit 加了if语句
prompt = ‘Tell me something,and I will repeat it back to you: ’
prompt += "\nEnter ‘quit’ to end the program. "
message = ‘’
while message != ‘quit’:
message = input(prompt)
if message != ‘quit’:
print(message)
#标志(在要求很多条件都需要满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动活动状态)
prompt = ‘Tell me something,and I will repeat it back to you: ’
prompt += "\nEnter ‘quit’ to end the program. "
active = True #标志 active为True,循环继续进行
while active:
if message == ‘quit’:
active = False
else:
print(message)
#break退出循环
#任何python循环中都可使用break语句。例如,可使用break语句退出遍历列表或者for循环
#查看用户去过哪些城市
prompt = ‘\nPlease enter the name of the city you have visited:’
prompt += “\n(Enter ‘quit’ when you are finished)” #运算符+=相当于存储在prompt中的字符串末尾附加一个字符串
while True:
city = input(prompt)
if city == ‘quit’:
break
else:
print(‘I would love to go to ’ + city.title() + ‘.’)
#在循环中使用continue(返回循环开头,根据条件测试结果决定是否继续执行循环)
#例题:1-10打印奇数
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
#循环从1-5
x = 1
while x <= 5:
print(x)
x += 1
#验证用户的同时将未验证的用户列表中提取出来,将其加入到已认证的用户列表中
unconfirmed_users = [‘alice’,‘brian’,‘candace’] #创建待认证的用户列表
confirmed_users = [] #创建一个空的用于存储已认证用户的列表
while unconfirmed_users: #while循环直到列表unconfirmed_user为空
current_user = unconfirmed_users.pop()
print(‘Verifying user:’ + current_user.title())
confirmed_users.append(current_user)
print(‘The following users have been confirmed:’)
for confirmed_user in confirmed_users:
print(confirmed_user.title())
#利用函数remove()删除列表中特定的值
pets = [‘a’,‘b’,‘c’,‘b’,‘d’,‘b’]
print(pets)
while ‘b’ in pets:
pets.remove(‘b’)
print(pets)
#第8章 函数
#定义函数
def great_user():
#’’‘显示问候语’’’
print(‘hello!’)
great_user()
age = 12
if age < 4:
price = 0
elif age < 65:
price = 5
elif age >= 40:
price = 5
print(‘your admission cost is $’ + str(price) + ‘.’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值