Python编程学习笔记(2)

嵌入式技术

1344人已加入

描述

第二章、变量和简单数据类型

2.1 运行hello_world.py时发生的情况

运行文件hello_world.py时,末尾的.py指出这是一个Python程序,因此编辑器将使用Python解释器 来运行它。Python解释器读取整个程序,确定其中每个单词的含义。例如,看到单词print 时,解释器就会将括号中的内容打印到屏幕,而不会管括号中的内容是什么。

编写程序时,编辑器会以各种方式突出程序的不同部分。例如,它知道print 是一个函数的名称,因此将其显示为蓝色;它知道“Hello Python world!”不是Python代码,因此将其显示为橙色。这种功能称为语法突出。

2.2 变量

在程序中可随时修改变量的值,而Python将始终记录变量的最新值。

message = "Hello Python world!"
print(message)
Hello Python world!
message = "Hello Python Crash Course world!"
print(message)
Hello Python Crash Course world!

2.2.1 变量的命名和使用

  • 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
  • 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
  • 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print。
  • 变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
  • 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。

尽量使用小写的Python变量名。在变量名中使用大写字母虽然不会导致错误,但避免使用大写字母是个不错的主意。

2.2.2 使用变量时避免命名错误

程序无法成功地运行时,解释器会提供一个traceback。traceback是一条记录,指出了解释器尝试运行代码时,在什么地方出现问题。

下面的程序注意错误类型:NameError: name 'mesage' is not defined

message = "Hello Python Crash Course reader!"
print(mesage)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

< ipython-input-3-c8f2adeaed02 > in < module >()
      1 message = "Hello Python Crash Course reader!"
---- > 2 print(mesage)


NameError: name 'mesage' is not defined

练习: 2-1 简单消息:将一条消息存储到变量中,再将其打印出来。2-2 多条简单消息:将一条消息存储到变量中,将其打印出来;再将变量的值修改为一条新消息,并将其打印出来。

simple_message = "Hello, Simple Message"
print(simple_message)
Hello, Simple Message
multi_message = "Multi Message 1"
print(multi_message)
multi_message = "Multi Message 2"
print(multi_message)
Multi Message 1
Multi Message 2

2.3 字符串

字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。

str1 = "Hello, String 1"
print(str1)
str2 = 'Hello, String 2'
print(str2)
str3 = '''Hello, It's String 3'''
print(str3)
Hello, String 1
Hello, String 2
Hello, It's String 3

2.3.1 使用方法修改字符串的大小写

name = "aDa loveLace"
#执行每个单词首字母大写的方法
print(name.title())
#转换为首字母大写的方法
print(name.capitalize())
#全部转换为大写的方法
print(name.upper())
#全部转换为小写的方法
print(name.lower())
Ada Lovelace
Ada lovelace
ADA LOVELACE
ada lovelace

2.3.2 合并(拼接)字符串

first_name = "ada"
last_name = "lovelace"
#字符串拼接
full_name = first_name + " " + last_name
print(full_name)
print("Hello, "+full_name.title()+"!")
#格式化字符串
name = "{} {}".format(first_name,last_name)
print(name)
ada lovelace
Hello, Ada Lovelace!
ada lovelace

2.3.3 使用制表符或换行符来添加空白

要在字符串中添加制表符,可使用字符组合t;要在字符串中添加换行符,可使用字符组合n。

print("t pythont Hellon t World t In t love t you!n")
python	 Hello
 	 World 	 I
 	 love 	 you!

2.3.4 删除空白

下例中,len()用来查看字符串的长度。

message = " Python is a good language. "
#去除左空格
print(message.lstrip(), len(message.lstrip()))
#去除右空格
print(message.rstrip(), len(message.rstrip()))
#去除两边的空格
print(message.strip(), len(message.strip()))
Python is a good language.  27
 Python is a good language. 27
Python is a good language. 26

2.3.5 使用字符串时避免语法错误

语法错误是指程序中包含非法的Python代码时,就会导致语法错误。

例如,在用单引号括起的字符串中,如果包含撇号,就将导致错误。这是因为这会导致Python将第一个单引号和撇号之间的内容视为一个字符串,进而将余下的文本视为Python代码,从而引发错误。

message = "One of Python's strengths is its diverse community."
print(message)
One of Python's strengths is its diverse community.
message = 'One of Python's strengths is its diverse community.'
print(message)
File "< ipython-input-12-a9250de55b39 >", line 1
    message = 'One of Python's strengths is its diverse community.'
                             ^
SyntaxError: invalid syntax

2.3.6 Python 2中的print 语句

在Python 2中,无需将要打印的内容放在括号内。从技术上说,Python 3中的print 是一个函数,因此括号必不可少。有些Python 2 print 语句也包含括号,但其行为与Python 3中稍有不同。在Python 2代码中,print可以包含括号,也可以不包含。

练习:

2-3 个性化消息:将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消息应非常简单,如“Hello Eric, would you like to learn some Python today?”。

2-4 调整名字的大小写:将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。

2-5 名言:找一句你钦佩的名人说的名言,将这个名人的姓名和他的名言打印出来。输出应类似于下面这样(包括引号):

Albert Einstein once said, “A person who never made a mistake never tried anything new.”

2-6 名言2:重复练习2-5,但将名人的姓名存储在变量famous_person 中,再创建要显示的消息,并将其存储在变量message 中,然后打印这条消息。

2-7 剔除人名中的空白:存储一个人名,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合"t" 和"n" 各一次。

打印这个人名,以显示其开头和末尾的空白。然后,分别使用剔除函数lstrip() 、rstrip() 和strip() 对人名进行处理,并将结果打印出来。

#2-3
famous_name = 'Albert Einstein'
print("Hello {}, would you like to learn some Python today?".format(famous_name))
#2-4
print(famous_name.lower())
print(famous_name.upper())
print(famous_name.title())
#2-5 & 2-6
famous_clause = 'A person who never made a mistake never tried anything new.'
print('''{} once said, “{}”'''.format(famous_name, famous_clause))
# 2-7
famous_person = '''
	
albert einstein	
  '''
print(famous_person.lstrip())
print('----------------------')
print(famous_person.rstrip())
print('----------------------')
print(famous_person.strip())
print('----------------------')
Hello Albert Einstein, would you like to learn some Python today?
albert einstein
ALBERT EINSTEIN
Albert Einstein
Albert Einstein once said, “A person who never made a mistake never tried anything new.”
albert einstein	

----------------------

	
albert einstein
----------------------
albert einstein
----------------------

2.4 数字

2.4.1 整数

在Python中,可对整数执行加(+)减(-)乘(*)除(/)求余(%)运算;使用两个乘号(**)表示乘方运算;使用括号来修改运算次序,让Python按你指定的次序执行运算。

print(2 + 3)
print(3 - 2)
print(2 * 3)
print(3 / 2)
print(3 % 2)
print(3 ** 2)
print(2 + 3 * 4)
print((2 + 3) * 4)
5
1
6
1.5
1
9
14
20

2.4.2 浮点数

Python将带小数点的数字都称为浮点数。小数点可出现在数字的任何位置。

print(0.1 + 0.1)
print(0.2 + 0.2)
print(2 * 0.1)
print(2 * 0.2)
print(0.2 + 0.1)
print(3 * 0.1)
0.2
0.4
0.2
0.4
0.30000000000000004
0.30000000000000004

上面最后两行的语句在所有语言都存在这种问题,没有什么可担心的。Python会尽力找到一种方式,以尽可能精确地表示结果,但鉴于计算机内部表示数字的方式,这在有些情况下很难。就现在而言,暂时忽略多余的小数位数即可

2.4.3 使用函数str() 避免类型错误

age = 38
message = "Happy " + age + "rd Birthday!"

print(message)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-16-a9d2b2541859 > in < module >()
      1 age = 38
---- > 2 message = "Happy " + age + "rd Birthday!"
      3
      4 print(message)


TypeError: must be str, not int
age = 38
message = "Happy " + str(age) + "th Birthday!"
print(message)
Happy 38th Birthday!
age = 38
message = "Happy {}th Birthday!".format(age)
print(message)
Happy 38th Birthday!

2.4.4 Python 2中的整数

在Python 2中,若要避免商被取整,务必确保至少有一个操作数为浮点数,这样结果也将为浮点数。

2.5 注释

注释让你能够使用自然语言在程序中添加说明。

2.5.1 如何编写注释

在Python中,注释用井号(#)标识。#号后面的内容都会被Python解释器忽略。具体可见上面代码段中的#用法。

2.5.2 该编写什么样的注释

编写注释的主要目的是阐述代码要做什么,以及是如何做的。在开发项目期间,你对各个部分如何协同工作了如指掌,但过段时间后,有些细节你可能不记得了。当然,你总是可以通过研究代码来确定各个部分的工作原理,但通过编写注释,以清晰的自然语言对解决方案进行概述,可节省很多时间。

要成为专业程序员或与其他程序员合作,就必须编写有意义的注释。当前,大多数软件都是合作编写的,编写者可能是同一家公司的多名员工,也可能是众多致力于同一个开源项目的人员。训练有素的程序员都希望代码中包含注释,因此你最好从现在开始就在程序中添加描述性注释。作为新手,最值得养成的习惯之一是,在代码中编写清晰、简洁的注释。

如果不确定是否要编写注释,就问问自己,找到合理的解决方案前,是否考虑了多个解决方案。如果答案是肯定的,就编写注释对你的解决方案进行说明吧。相比回过头去再添加注释,删除多余的注释要容易得多。

2.6 Python之禅

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分