Python初学笔记(一)
python 字典
通过字典来完成翻译/转换
例子:
目的:输入1234等数字,通过python的字典功能将数字转换为"One",“Two”,"Three"等对应英文单词
代码:
…
//A code block
phone = input(‘Phone: ‘)
digital_mapping = {
“1”:“One”,
“2”:“Two”,
“3”:“Three”,
“4”:“Four”
}
output = ’ ’
for character in phone:
output += digital_mapping.get(character,’!’) + ’ ’
print(output)
…
代码运行结果:
Phone: 1234
One Two Three Four
Phone:2345
Two Three Four !
python keyword argument(关键字参数)
例子:
…
//A code block
def great_user(first_name,last_name):
print(f’ Hi! {first_name} {last_name}’)
第一种方式:位置参数,也就是参数根据对应位置赋值
great_user(‘John’,‘Smith’)
第二种方式:关键字参数,根据关键字来赋值,与参数所在位置无关,具有更好的可读性
great_user(last_name = ‘Smith’,first_name = ‘John’)
…
利用keyword argument 可以使代码在赋值的时候具有更好的可读性
python try except
例子:
try:
age = int(input('Age: '))
print(age)
except ValueError:
print(‘Invalid value’)
用这段代码来理解 try 与 except
如果只有
age = int(input('Age: '))
print(age)
则运行后会报错–ValueError
但用了 try 和 except 就会
显示 Invalid values 使得程序继续运行下去
避免了因为报错而停止整个程序的运行