《Python编程:从入门到实践》第2-第7章学习小结

Geany中无法添加中文注释:

Python默认使用ASCII标准编码,如果没有其他编码提示,要定义一个源代码编码:

# coding=<encoding name>

# -*- coding: <encoding name> -*-

所以,如果要添加中文注释,要先写上# coding=utf-8或者# -*- coding: utf8 -*-

Geany中无法打印中文:

文档->设置文件编码->Unicode->选择Unicode(UTF-8)。 【注意,这个设置仅对当前文件有效,新文件需要再次设置】

 

学习笔记(Geany的便签很方便> <)

rstrip:删除末尾空格
lstrip:删除开头空格
strip:删除两端空格

append()将元素添加到列表末尾
insert()可在列表的任何位置添加新元素
del删除某个元素(del motor[0])(删除某一位置上的元素)
术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。但也可以弹出指定位置的元素:popped_motor=motor.pop(1) #弹出位置1的元素。每当使用pop()时,被弹出的元素就不再在列表中了。
如果要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop():del motor[0]就直接将第一个元素删除了,无法将其赋给某个变量继续使用,而motor_popped=motor.pop(0)就可以通过将第一个元素赋给motor_popped继续使用。
remove:删除列表中的特定值(pets.remove(‘cat’))

==
!=
and:两个都成立
or:至少一个成立
in:在列表中
not in:不在列表中

if
if-else
if-elif-else
if-elif...
if...

★如果只输出数字,就直接print(变量);如果输出数字+文字,那么要str(变量)

列表、元组、字典

字典:{}
遍历字典的键-值时:.items()
只遍历字典的键时:.keys()
只遍历字典的值时:.values()

为剔除重复项,可使用set:for language in set(favorite_languages.values()):

函数input()让程序暂停运行,等待用户输入一些文本。在()中的内容是打印在屏幕上的提示词,并不是将输入内容储存在()里的变量中。

设置while的标志,使得代码更加简洁。(True or False)

break
contine

看书随手写的代码(全混在一起了,大概只有我自己能看懂> <,留个纪念~

#-*- coding: utf-8 -*-
message = "hello python world"
print(message)
message = "hello my python world"
print(message)
message = "l said l love you'"
print(message)
name = "ada lovelace"
print(name.title()) 
print(name.upper())
print(name.lower())
first_name="ada"
last_name="lovelace"
full_name=first_name+last_name
print(first_name)
print(last_name)
print(full_name.upper())
fulll_name2=first_name+' '+last_name
print(fulll_name2.title())
sentence='hello '+fulll_name2+'!'
print(sentence)
print('\thello '+fulll_name2+'!')
print('\nhello '+fulll_name2+'!')
language='python '
print(language+'!')
print(language.rstrip()+'!')
print(language+'!')
language=language.rstrip()
#删除末尾空格
print(language+'!')
namesaying='john said, "you are good"'
print(namesaying)
hisname='jonh'
saying='"you are good"'
print(hisname+ ' said, '+saying)
a=0.1+0.1
print(a)
age=20
celebrate='happy '+str(age)+'rd birthday'
print(celebrate.title())
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles)
print(bicycles[0])
print(bicycles[-2])

motor=['honda','yamaha','suzuki']
print(motor)
print(motor[0])
motor.append('ducati')
print(motor)
motor.insert(0,'ahhhh')
motor.insert(3,'ahhhh')#将ahhhh储存在1的位置上
print(motor)
del motor[0]
print(motor)
popped_motor=motor.pop()#弹出末尾的元素
print(motor)
print(popped_motor)
popped_motor=motor.pop(1)#弹出位置1的元素
print(motor)
print(popped_motor)
motor=['honda','yamaha','suzuki']
expensive='suzuki'
motor.remove(expensive)
print(motor) 
print("\nA " + expensive.title() + " is too expensive for me.")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:") 
print(cars) 
print("\nHere is the sorted list:") 
print(sorted(cars)) 
print(sorted(cars,reverse=False)) #顺字母顺序
print(sorted(cars,reverse=True))  #逆字母顺序
print("\nHere is the original list again:") 
print(cars)
print(cars.reverse())#倒序打印
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
      print(magician)
for value in range(1,6):
	print(value)
numbers=list(range(1,6))#转化成列表
print(numbers)
even_numbers = list(range(2,11,2)) 
print(even_numbers)#指定步长
squares=[]
for value in range(1,5):
	square=value**2
	squares.append(square)
print(squares)
squares=[value**2 for value in range(1,11)]#列表解析
print(squares)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]: 
 print(player.title())
available_toppings = ['mushrooms', 'olives', '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('add some '+requested_topping+' in the pizza')
	else:
		print("don't have")
print('\nthis is your pizze')
liyifan={}
liyifan['height']=180
liyifan['weight']=200
liyifan['girlfriend']='chency'
print("liyifan's information: ")
print(liyifan)
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']))
alien_0['speed']='fast'
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']))
for k,v in alien_0.items():
	print('\nkey is '+str(k))
	print('value is '+str(v))
print('\n')
for key in alien_0.keys():#for key in alien_0
	print(key)
print(alien_0.keys())#返回一个列表,其中包含字典中的所有键
del alien_0['speed']
print('\n')
print(alien_0)
favorite_languages = { 
 'jen': 'python', 
 'sarah': 'c', 
 'edward': 'ruby', 
 'phil': 'python', 
 } 
for name in sorted(favorite_languages.keys()):
	print('hi '+name)
print('\n')
for language in favorite_languages.values():
	print('is '+language)
print('\n')
for language in set(favorite_languages.values()):
	print('is '+language)
alien_0 = {'color': 'green', 'points': 5} 
alien_1 = {'color': 'yellow', 'points': 10} 
alien_2 = {'color': 'red', 'points': 15} 
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
	print(alien)#alien是一个字典,aliens是一个以字典为元素的列表
#在列表中储存字典
aliens=[]

#创建三十个绿色的外星人
for alien_number in range(30):
	new_alien={'color':'green','point':5,'speed':'slow'}
	aliens.append(new_alien)
	
for alien in aliens[:5]:
	print(alien)

#在字典中储存列表
pizza = { 
 'crust': 'thick', 
 'toppings': ['mushrooms', 'extra cheese'], 
 } 
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " + 
 "with the following toppings:") 
for topping in pizza['toppings']: 
 print("\t" + topping)

#在字典中储存字典
users = { 
 'aeinstein': { 
 'first': 'albert', 
 'last': 'einstein', 
 'location': 'princeton', 
 }, 
 'mcurie': { 
 'first': 'marie', 
 'last': 'curie', 
 'location': 'paris', 
 }, 
 } 
for username, user_info in users.items(): 
 print("\nUsername: " + username) 
 full_name = user_info['first'] + " " + user_info['last'] 
 location = user_info['location'] 
 print("\tFull name: " + full_name.title()) 
 print("\tLocation: " + location.title())
prompt='tell me something and I will repeat it back to you, \n'
prompt+='if you say "quit" I will stop\n'
message=input(prompt)
while message !='quit':
	 print(message)
	 message=input(prompt)
	 print('\n')
index=True
while index!=False:
	message=input()
	
	if message=='quit':
		index=False
	else:
		print(message)
while True:
	message=input()
	
	if message=='quit':
		break
	else:
		print(message)
responses = {} 
# 设置一个标志,指出调查是否继续
polling_active = True 

while polling_active: 
 # 提示输入被调查者的名字和回答
 name = input("What 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 + ".")
for name in responses.keys():
	print(name)
for res in responses.values():
	print(res)

一点想法:

这本书对于初学者真的非常友好,里面的例子很有趣,而且在涉及到具体知识点的时候,会讲到它的实际应用,就会让人感觉更加具体和实用。但是对于已经学过C语言基本语法的人(就是我)来说,可以翻的快一些,不用那么仔细。在这个过程中,可以类比在C中的一些概念。另外,在C中的语法很严谨,而且能感受到它在底层的状态(a feeling),而在python中侧重便捷性。所以,在写python时也可以回忆回忆实际上底层是怎样运行的。(不知道这样讲是不是合理^^) 此外,我感觉循环语句for、while等放在一起讲,列表、元组、字典放在放在一起讲,输入和输出放在一起讲更加有连贯性(可能是习惯了C语言的套路)。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值