print("Hello World!")
Hello World!
print("Hello World!")
Hello World!
a = 0x0608
print(a )
1544
整数
- 整数通常指不带有小数部分的数字,包括自然数,0,负数等
- 可以表示任意大的数
- 整数的进制:
- 十进制
- 二进制
- 0b
- 八进制
- 0o
- 十六进制
- 0x
# 十进制转二进制
a = 100
b = bin(a)
print(b)
0b1100100
# 十进制转八进制
a = 100
b = oct(a)
print(b)
#十进制转16进制
c = hex(a)
print(c)
0o144
0x64
# 检验以上结果是否正确
a = 0o144
print(a)
b = 0x64
print(b)
100
100
浮点数
- 定义:
- 表现形式:
- 常见小数
- 科学计数法,小数乘以10为底的指数,指数可以为负数
#科学计数法
a = 3.243234e3
print(a)
3243.234
复数
- 由实部和虚部组成,中间用‘+’号链接,虚部后跟‘j’表示
- 例如 :3+4j 23,12 + 43.2j
# 复数
a = 3. + 4j
print(a)
(3+4j)
2.字符串类型
什么是字符串
- 表示文本信息的一种形式
- 排列有序
- 在非注释中,凡是引号括起来的部分都是字符串
- 引号类型
- 单引号: ‘’
- 双引号:""
- 三单引号:’’’’’’
- 三双引号: “”""""
引号的区别
- 单双引号没有区别
- 三单引号 和 三双引号 之间没有区别
- 三引号常用来表示多行字符串信息,或者在程序函数内部函数体开头表示函数说明
a = '''
王啊王
'''
print(a)
王啊王
# 字符串中出现引号
# 比如 Let's go
a = 'Let's go'
print(a)
File "<ipython-input-18-c3cfddb251e8>", line 3
a = 'Let's go'
^
SyntaxError: invalid syntax
# 字符串 中出现引号 ,需要换一种引号引起来
a = "Let's go"
print(a)
Let's go
# 字符串 中出现引号 ,需要换一种引号引起来
a = '''Let's go'''
print(a)
Let's go
# 字符串 中出现引号 ,需要换一种引号引起来
a = """Let's go"""
print(a)
Let's go
转义字符
- 转义字符L字符串中一些不太好表示的符号,比如换行,制表符,连同一些需要特殊表示的符号,被如单引号,为了表示这些符号,需要用一些特殊形式,俗称转义,需要转义符号,俗称转义字符
- 转义字符::
- 单引号:’
- 双引号:"
- 响铃: \a
- 反斜杠: \
- 换行:\n
- 水平制表符:\t
- 垂直制表符:\v
- 倒退:\b
- 空字符串:字符值为0:\0
- unicode 16位的十六进制值:\uxxxx(注意,是四个数字)
- Unicode 32位的十六进制值:\uxxxx xxxx(注意,u后面是8位值)
- 十六进制值:\xXX(注意:第一个x是必须有的,后边大X表示十六进制)
- 八进制值:\Oxx
- 转义字符::
# 字符串 中出现引号 ,需要换一种引号引起来
a = 'Let\'s go'
print(a)
Let's go
3.布尔类型
String 类型的API
- API 应用程序接口,是第三方已经做好的继承好的程序功能,我们需要的仅仅是使用/调用,目的是最大程度上减少使用者的开发时间,提高使用者的开发效率
- 不重复造轮子
1.一般函数
- startswith/endswith
- 判断字符串是否以特定字符串开头或者结尾
- count
- 计数,计算一个字符串从某字符串出现的次数
- find
- 查找字符串中子字符串出现的位置
- 能查到,返回第一个查到的位置
- 查不到结果,返回 -1
# 判断字符串开头或者结尾
s = "I comes from china"
s.startswith("I")
True
# count 例子
s.count("789")
0
s.count("rom")
1
s.find("I")
0
## 查手册:
help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Use keyword.iskeyword() to test for reserved identifiers such as "def" and
| "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| Splits are done starting at the end of the string and working to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace remove.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(x, y=None, z=None, /)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
2.判断字符串
- 起一定判断功能的字符串
- islower/isupper
- 判断字符串是小写字母还是大写字母
- 要求全部是小写或者大写才返回真值
- isdigit
- 判断字符串是否是全部由数字组成
- isalpha
- 判断字符串是否全部由字母组成
- alpha 是指英文字母表里的内容
# islower/isupper
s = "My first love is wwwwww"
s.islower()
False
s.isupper()
False
s
True
# isdigit
s.isdigit()
False
sss = "234232342342"
sss.isdigit()
True
s3 = "23423 is your qq?"
s3.isdigit()
False
# isalpha 空格不是alpha
s.isalpha()
False
sss.isalpha()
False
s5 = "SDFSFSDFSFSFDFGRER"
s5.isalpha()
True
3 操作类函数
- lower/upper
- 把字符串转换成大小写
- strip/lstrip/rstrip
- 去掉空格
- swapcase
- 字符串中的字符交换大小写
字符串格式化
- 字符串按照一定的格式进行打印或者填充
- 格式化的分类:
- 使用%进行格式化
- 使用 format函数,近年来比较流行
# 字符串格式化例子
s = "My name is wdh, my age is 20,i am 170,60kg"
print(s)
My name is wdh, my age is 20
s = "My name is %s, my age is %d,i am %.2f,%dkg" % ('wdh',21,169,59)
print(s)
My name is wdh, my age is 21,i am 169.00,59kg
利用 % 进行格式化
# %s 表示简单字符串
s = "My age is %s" % "wdh"
print(s)
My age is wdh
# 当只有一个需要替换的时候,可以省略括号
s = "My age is %s" % ("wdh")
print(s)
My age is wdh
# %d,表示一个数字(整数)
s = "my age is %d" % 28
s
'my age is 28'
# %d 只能表示整数。如果后边实际内容是小数,则进行取整操作
# 取整是直接取整,舍弃后面的小数
s = "my age is %d" % 28.8
s
'my age is 28'
# %f 表示浮点小数
s = "i am %fkg" % 86.11
s
'i am 86.110000kg'
# 可以对小数的格式 进行限制,在字符f前如果出现 ‘.x’,其中x表示一个整数,则此时表示浮点数小数点后出现的位数
s = "i am %.2fkg" % 66.696
s
'i am 66.70kg'
s = "i am %.8fkg" % 66.696
s
'i am 66.69600000kg'
# 如果需要格式画的信息多于一个,则用括号把数据括起来就行了
# 在字符串中表示%怎么办?
s = "sdfsf%sdfsdfs"
s
'sdfsf%sdfsdfs'
占位符的种类:
- %s 字符串
- %r 字符串,但是是使用repr而不是str
- %c 整数转换为单个字符
- %d 十进制整数
- %u 无符号整型
- %o 表示八进制
- %x 十六进制,字母为小写(x为小写)
- %X 十六进制,字符为大写(X为大写)
- %e 浮点数(E为小写),例如:2.87e+12
- %E 浮点数(E为大写),例如:2.87E+12
- %f,%F 浮点数十进制形式
- %g,%G 十进制形式浮点或者指浮点自动转换
- 格式前面出现整数表示此占位符所占位置的宽度
- % 格式字符前边出现‘-’表示左对齐
- % 格式字符前边出现‘+’表示右对齐
- 0位数不足用‘0’补齐
- width表示宽度
- pricision精度
"i am %10dlog" % 13
'i am 13log'
"i am %20s" % "sdfsdsd"
'i am sdfsdsd'
"i am %-20s" % "sdfsdsd"
'i am sdfsdsd '
"i am %010d" %22
'i am 0000000022'
"i am %7.4fkg" %86.43
'i am 86.4300kg'
#对于float前面的占位宽不起作用
"i am %07.4fkg" %86.43
'i am 86.4300kg'
布尔变量
- 表示真假,行或者不行,是或者不是
- True/False
- 在编程当中,需要大量判断真假,是非,对错
1 > 9
False
# 字符串可以拿来直接比较
"ff" > "b"
True
if ( 3 > 8 ):
print("yes")
else:
print("No")
No
True
True
b = False
b
False
# 如果布尔值作为数字参与运算,那么所有非0的数字都为True,但是,反之如果True作为数字参与运算的时候,True表示1
True * 3
3
False + 8
8
if 32:
print("true")
true
None
- 是一个特殊的常量
- 不表示任何类型,通常用来占位,或者变量解除绑定,None于任何其他的类型进行比较永远返回False
- 作用
- 占位
- 解除变量绑定
# None的例子
a = 353
print(a)
a = None
print(a)
353
None
#None 必须正确书写
a = none
print(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-78-e6a2f46dd1c7> in <module>
1 #None 必须正确书写
----> 2 a = none
3 print(a)
NameError: name 'none' is not defined
1-6 运算符
- 运算符就是为数据提供运算链接的符号
1.算术运算符
-
- ,-,/,%,//,*
# + - *,三个符号跟我们日常生活中的符号含义一致
# 表达式:由一个数字或者其他对象或者多个数字或者对象和运算符构成,通常是让计算机做一些事情并返回结果
a = 4+5 # 把4和5相加得出的值赋给a
print(a)
a = 7-2
print(a)
a= 8*6
print(a)
9
5
48
# '/'代表除法
# 在python2 和python3中有些区别,此处以python3为准
# 两数相除,结果为浮点数
a = 4/2
a
2.0
a = 5/2
a
2.5
a = 5.3 / 2
a
2.65
a = 4/3
a
1.3333333333333333
# '//'(floor,地板除)
# 两数相除,得到的结果取整
# 并不意味着得到的结果一定是整数
# 如两整数正好结果为整数,则得到的整数,否则出现浮点数
# 一下例子,量整数相除,结果正好除尽,得到整数结果
a = 4//2
a
2
#两数中包含小数,结果为浮点数
a = 4.0 // 2
a
2.0
# 两整数相除,无论是否除尽,结果都是整数
a = 25//3
a
8
a = 25//3.0
a
8.0
# ‘%’表示取余(取模,模)
# 5除以3 商1余2
# 5除以2 商2余1
7%3
1
14 % 5
4
3.125% 1.5
0.125
# ‘**’表示幂指数,求一个数的多少次幂
4**2
16
3**3
27
2**8
256
算数运算符的优先级
- 三个等级
- **
- *,/,%,//
- +,-
- 如果有括号,先计算括号内表达式
#1.先计算 4**2
#2.再计算3*16 和 5//2
#3.从左向右开始计算
2 - 3*4**2+5//2
-44
#优先计算6-5
2 - 3*4**(6-5)//2
-4
### 表达式中如果出现浮点数,整数等,则计算结果为浮点数
# 算式中包含浮点数,则结果为浮点数
3 + 6.8
9.8
练习:
- 温度转换(华氏温度,摄氏温度,开氏温度)
- 摄氏温度:5.0/9.0*(华氏温度-32)
- 开氏温度:5.0/9.0*(华氏温度-32)+273.15
- 今天摄氏温度23度,求华氏温度和开氏温度
- 审题:摄氏温度23=5.0/9.0(华氏温度-32)》239.0/5.0=华氏温度-32》华氏温度=23*9.0/5.0 + 32
- 然后把求到的华氏温度带入开氏温度公式,就可以求出开氏温度
s = 23
h = s*9.0/5.0 + 32
k = 5.0/9.0*(h-32)+273.15
print("摄氏:%d" % s )
print("华氏温度:%f" % h)
print("开氏温度:%f" % k)
摄氏:23
华氏温度:73.400000
开氏温度:296.150000
2 赋值运算符
- 为python变量提供赋值运算功能的符号
- =,+=,-=,/=,%=,**=,//=
# ‘=’,为python变量提供基本的赋值功能
# 赋值符号的作用:
# 当没有此变量时,创建一个变量,同时把变量绑定到这个对象上
# 当变量存在时,改变此变量关联的对象
# 用变量访问此变量关联的对象
a = 32 #把32赋值给变量a
# python中允许批量赋值
#左右数量必须一致
#不同变量和值用逗号隔开
a,b,c=1,2,3
print(a)
print(b)
print(c)
1
2
3
#python允许两个变量进行交换
a = 100
b = 200
print(a)
print(b)
100
200
a,b = b,a
print(a)
print(b)
200
100
# a+=b ==> a = a + b
a = 1
a += 4
print(a)
5
# 其他符号以此类推
练习:面积体积求值
- 半径为 r = 2.5cm的圆,求周长和面积
- 如果是球,求其体积
- 分析:
- 周长公式: l = 2* pi* r
- 面积:m = pi x r^2
- 体积: v = 4 x pi x r^3/3
# 作业练习
# 1.我们需要pi的值,最好用一个变量来表示
pi = 3.1415
r = 2.5
l = 2 * pi * r
m = pi * r ** 2
v = 4 * pi * r ** 3 / 3
print("周长:%f" % 1)
print("面积:%f" % m)
print("体积:%f" % v)
周长:1.000000
面积:19.634375
体积:65.447917
例子,求当前时间
- 从今天00:00:00 起,已经过去了28762秒,求现在是几时几分几秒
- 分析:
- 一个小时是3600秒
- 一分钟是60s
- 如果我们知道总秒数,对小时的秒数求整就应该是小时,求余就是剩下的分秒对应的秒数,"//"
- 对剩下的秒数用60求整,就会的到分钟数
- 剩下的就是秒数
s_sum = 28762
clock_sec = 3600
minu_sec = 60
clock = s_sum // clock_sec
s_sum = s_sum % clock_sec
minu = s_sum // minu_sec
s_sum = s_sum % minu_sec
print("现在是 %d时 %d分 %d秒" % (clock,minu,s_sum))
现在是 7时 59分 22秒
3.比较运算符
- 为我们提供比较功能的运算符
- 特点是:最后的结果是真或者假,即布尔值
<,>,<=,>=,==,!= - 这些符号和C语言中的含义相同
# == 检查操作是否等于
b = 4 == 6 # 先计算表达式,即对4==6进行判断,然后判断结果赋值给b
b
False
4 逻辑运算符
- 逻辑运算就是 对布尔值进行运算
- and,or,not
- 逻辑运算的短路问题:
- 在逻辑运算过程中,-旦结果已经确定,则不进行剩下的计算而是直接返回结果
# and 逻辑与
# 如果不能理解,可以把True看成数字1,False看做数字0,and就是乘号
True and False
False
True and True #可以理解为左右布尔值相乘
True
a = 7
b = 2
c = 8
a < b and b > c
False
# or 逻辑或
# 可以把True看做数字1,False看做数字0,则or就应该被看做 + 号
False or True # 0 + 1
True
True or True #可以理解为左右布尔值相加
True
# not 逻辑非
# True看做1,False看做0,则not看做取反
not True
False
### 特殊运算符
- is
- is not
- del
# is判断两个变量,对象是否是同一个
# 下面的例子,两个变量具有同一个值,但是否指向/绑定同一个对象呢?
# 两个对象/变量是否是is的依据是,id值是否一样
a = 7897 #用的时候临时创建
b = 7897
a is b # is 操作符返回布尔值
False
id(a) # 查看a绑定的对象的编号
140107648900080
id(b)
140107648900176
a = b
a is b
True
print(id(a))
print(id(b))
140107648900400
140107648900400
# Python 对一些初级的,常用的对象,放入内存中,供大家使用
a = 2 #一直在内存中,直接使用
b = 2 #一直在内存中,直接使用
a is b
True
print(id(a))
print(id(b))
94359883973696
94359883973696
# is not 跟is操作符正好相反
a is not b
False
# del 用于删除变量,同事解除与对象的关联,如果可能则释放对象
print(b)
2
# 因为已经把b删除掉了(释放内存),所以再次使用b的时候,出现name error
del b
print(b)
# 如果 有多个变量使用同一个id则 del操作不会真正删除掉id
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-143-9a0533abae4f> in <module>
1 # 因为已经把b删除掉了(释放内存),所以再次使用b的时候,出现name error
----> 2 del b
3 print(b)
4 # 如果 有多个变量使用同一个id则 del操作不会真正删除掉id
NameError: name 'b' is not defined
a = b = 4
print(a)
print(id(a))
print(b)
print(id(b))
del b
print(a)
print(id(a))
print(b)
print(id(b))
4
94359883973760
4
94359883973760
4
94359883973760
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-144-9e6261ff1f70> in <module>
7 print(a)
8 print(id(a))
----> 9 print(b)
10 print(id(b))
NameError: name 'b' is not defined
# 基本输入输出
- input
- print
# input: 从标准设备读取一个字符串,在python里末尾的换行符会被自动删除
# 标准输入设备:一般指键盘
# 标准输出设备:屏幕
input("请输入您的年龄,按回车键结束:")
请输入您的年龄,按回车键结束:20
'20'
age = input("请输入您的年龄,按回车键结束:") # 输入的内容赋给age,这里输入的内容是被作为字符串处理的,所以age是个字符串
print("您的年龄是 %s" % age)
请输入您的年龄,按回车键结束:20
您的年龄是 20
print("您的年龄是 %d" % age)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-147-346aa7de2c39> in <module>
----> 1 print("您的年龄是 %d" % age)
TypeError: %d format: a number is required, not str
# print 输出/打印信息到标准输出设备
print("my name is wdh")
my name is wdh
print("My age is: ",28)
My age is: 28
print("My age is: ",28,'sdfssfgdf')
My age is: 28 sdfssfgdf
分支语句
- 程序可以由种结构组成全部:程序结构 = 顺序 + 分支 + 循环
- 顺序:程序从上到下一行一行执行,一行执行完之后才会继续下一个行
- 分支:通过一个判断条件,不同的结果对应不同的处理程序段
- 循环:多次重复执行相同的或者相似的代码
if 语句
- 判断一个条件,当条件成立,则执行相应的程序代码段
- 语法如下:
if (条件表达式) :
程序处理模块 - python 用缩进来表示程序结构或者代码的层级关系
- 可以使用tab键或者空格
- 一个tab键表示几个空格可以设置
- python2中,只要空格数相等就可以,tab和空格可以混用
- python3中,不能混用,要么用空格,要么用tab,一般推荐使用tab
# 例子,假如 3< 56,则打印出字符串“True”
if( 3<56 ):
print("True")
True
if( 3>56 ):
print("True")
# pass语句,占位符号,不执行任何语句,不起任何实际作用
if (3<9):
pass
# if 语句案例
# 老师对大家的考试的程序进行评定,采用ABCDE五级进行评定,A是最好成绩
# 如果90分(包括此分数)以上,则输出A
# 如果80分(包括此分数)以上,则输出B
# 如果70分(包括此分数)以上,则输出C
# 如果60分(包括此分数)以上,则输出D
# 其余,则输出E
# 考试程序,由自己给出,存入变量
#以下代码 不符合题目要求
score = 87
if (score>=90):
print("A")
if (score>=80):
print("B")
if (score>=70):
print("C")
if (score>=60):
print("D")
if (score<60):
print("E")
B
C
D
# 以下代码满足要求
score = 87
if (score>=90):
print("A")
if (score>=80 and score<90):
print("B")
if (score>=70 and score<80):
print("C")
if (score>=60 and score<70):
print("D")
if (score<60):
print("E")
B
if…else…
- 假如条件满足,则执行if后面的语句,否则,执行else后面的语句
# 判断一个学生多成绩,如果大于60分,则学生成绩及格,否则,重考
score = input("请输入您的成绩:")
#此处输入内容被作为字符串处理了,所以使用score时需要转换
#score = int(score)
if(score>=60):
print("您已经及格!")
else:
print("对不起,您需要重考!")
请输入您的成绩:20
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-7ab17da7d300> in <module>
3 #此处输入内容被作为字符串处理了,所以使用score时需要转换
4 #score = int(score)
----> 5 if(score>=60):
6 print("您已经及格!")
7 else:
TypeError: '>=' not supported between instances of 'str' and 'int'
#重新写:
score = input("请输入您的成绩:")
#此处输入内容被作为字符串处理了,所以使用score时需要通过int对象把字符串转换成整数数字
score = int(score)
if(score>=60):
print("您已经及格!")
else:
print("对不起,您需要重考!")
请输入您的成绩:20
对不起,您需要重考!
# 输入学生成绩,大于等于90则输出A,否则判断是否大于60,如果大于60则输出及格,否则输出不及格
score = input("请输入您的成绩:")
#此处输入内容被作为字符串处理了,所以使用score时需要通过int对象把字符串转换成整数数字
score = int(score)
if(score>=90) :
print("A")
print("Your are the best!")
print("Thank you!")
else :
if(score>=60):
print("成绩及格")
else:
print("成绩不及格")
请输入您的成绩:20
成绩不及格
### else 跟谁配对?
score = 87
if ( score > 90 ):
if(score>95):
print("Your are the best")
else:
print("just soso")
just soso
练习:if语句后者if…else语句,模拟上海出租车收费系统
- 3公里以内,收费基本起步费用 13元
- 超出3公里,则2.3元/km
- 空驶费,超出15公里,每公里加收单价的50%空驶费,即 3.45元/km
- 要求:输入驾驶里程后计算费用
#1. 要求用户输入总里程等于3km,则输出13元
#3. 如果大于3km并且小于等于15km,则收取13 + (里程数-3)*2.3
#4. 如果大于15公里,则13 + 12*2.3 + (里程数-15)*3.45
#5. 输出费用
km = input("请输入行驶里程数:")
km = int(km)
if(km<=3):
cost = 13
print("费用:%0.2f" % cost)
else:
if(km<=15):
cost = 13+(km-3)*2.3
print("费用:%0.2f" % cost)
else:
cost = 13+12*2.3+(km-15)*3.45
print("费用:%0.2f" % cost)
请输入行驶里程数:20
费用:57.85
三元操作符
- 元:操作数的意思,所谓三元,就是一个操作符带动三个操作数一起运算
- 原本没有python没有三元运算符
- 语法: x if 条件 ele y
# 三元运算符示例
a = 34 if 3<5 else 1
a
34
a = 34 if 3>5 else 1
a
1
作业:三元运算符
- a,b两数由用户输入
- 比较大小,把最大值存入变量c
# 分析:
# 1.用户输入可以用input函数,然后用int转换
# 2. 比较两个数,把最大值存入c
a = input("请输入数字A:")
a = int(a)
b = int(input("请输入数字B:"))
c = a if a>b else b
c
请输入数字A:35
请输入数字B:22
35
### 要求用三元运算符求最大值
- 要求:
1. a,b,c由用户输入是哪个
2. 比较大小,最大值输出
a = int(input("请输入A:"))
b = int(input("请输入B:"))
c = int(input("请输入C:"))
e = (a if a>b else b)
d = (e if e>c else c)
d
请输入A:12
请输入B:45
请输入C:6
45
前提只是
list
- 列表:用来盛放/表示一串性质相同或者相似的数据,这些数据组成有序的一种排序方式
- 一个列表可以盛放:数字,字符串,列表,或者其他复杂的结构
# 列表定义
# 直接表示列表,需要用中括号括起来,中间数据用逗号隔开
L1 = [1,2,3,4,5]
L1
[1, 2, 3, 4, 5]
L2 = [5,1,"你好!",6.8,[3,6,8]]
L2
[5, 1, '你好!', 6.8, [3, 6, 8]]
range
- 一个函数
- 产生一个有规律的由数字组成的列表
- 使用包含三个参数: range(start,end,step)
- start: 开始数字,以后生成列表里,包含这个数字作为第一个数字,默认为0
- end: 结束数字,这个数字不包含在range生成的列表里,例如range(1,5) 就是生成[1,2,3,4],不包含end
- step: 步长,即每次增加多少,默认为1
- python2: range生成结果就是列表,同时有xrange函数,功能类似
- python3:没有xrange,生成的结果就是迭代器,不是列表,教学上为了易于理解,初步认为是生成的列表
a = range(1,6)
# a==[1,2,3,4,5]
a = range(2,12,3)
# a==[2,5,8,11]
For循环
- 程序三个结构:顺序,分支,循环
- 循环:重复做一些性质相同或者相似的事情
- Python循环:for,while
- for:用关键字for来表示
- for循环特点:有一个清晰的循环次数,或者清晰的循环结束标志等
- 语法:
for i in xxx:
循环语句模块
L1 = [1,2,3,4,5]
# 对于在L1中每一个元素,我们给这个元素临时用变量idx表示,执行打印操作
for idx in L1:
print(idx)
1
2
3
4
5
#列表由range函数生成
L2 = range(1,6) # 这里不包含6
for idx in L2:
print(idx)
1
2
3
4
5
作业: 1-50的数求和
- 1-50的数字增长有规律,次数明确
- 是个for循环
- 列表适合用range生成
# 生成存放结果的变量
mySum = 0
for idx in range(1,51):
mySum += idx
print(mySum)
1275
while循环
- 当满足一定条件的时候才循环,具体循环多少次数没有具体规定或者规划
- 语法:
while(循环条件):
循环体
示例:银行利息
- 10000本金
- 每年利息收入7%
- 多少年后本金会超过12000
- 分析:
- 循环问题
- 没有明确循环次数
- 循环条件确定:本金不超过13000
- while
# 让我们求年限,我们用一个变量来存储答案并初始化
year = 0
money = 10000
while(money<=13000):
money *= (1 + 0.07 )
year += 1
print("Year is %d" % year)
Year is 4
示例:累加求和
- 1_50 累加求和
- while 循环必须用
- 分析:
- 用计数来表示数字,从1开始,每次增长1,只要小于51,就把数字和总和相加
- 循环条件:n 小于51
- 每次n都要增加1
- 每次n都要跟综合相加
# 存放综合
mySum = 0
# 计数器
n = 1
while n < 51 :
mySum += n
n+= 1
print("Summary is %d" % mySum)
Summary is 1275
break语句
- 英文原意就是中断循环的意思,在python中,保持了英文的原意
- 无条件终止循环并跳出循环体
示例:
- 在50_100之间查找第一个可以被9整除的数
- 对于此类业务,优先选用for
- 要求找到第一个==>找到第一个就行该退出
- 退出==>break
for idx in range(50,101):
# 被9整除如何表示?
# 如果用9取余等于0,则表示能被整除
print(idx)
if(idx % 9)==0:
print(idx)
break
50
51
52
53
54
54
对于嵌套多重训话你,break语句值退出跟他最近的一次循环
练习: 输出9*9乘法表
- 如果相乘的积大于36,则不需要显示
- 乘法表是一个典型的双重for循环结构
- 如果乘积大于36,我们结束本轮循环
- 结束用break
# 不能使用print语句,因为print语句默认输出后悔换行
# 在sys模块中有write可以使用
import sys
# 负责乘法表的行数
for i in range(1,10):
#负责乘法表列数的循环
for j in range(1,10):
if(i*j>36):
break;
sys.stdout.write(str(i*j))
sys.stdout.write("\t")
sys.stdout.write("\n")#此处用print打印空格也可以起到换行效果,print(" ")
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35
6 12 18 24 30 36
7 14 21 28 35
8 16 24 32
9 18 27 36
continue语句
- continue 含义:继续循环
- 使用环境:当我们已经确定不需要继续本轮循环的时候使用
案例:累加求和
- 1_100累加求和
- 只有当数字为奇数的时候才累加
- 分析:
- 累加求和==>for循环
- 奇数==>n%2!=0
- 奇数就累加,偶数就进行下一轮循环
mySum = 0
for idx in range(1,100):
if idx % 2 ==0 :
# continue继续的含义就是继续下一轮循环
continue
mySum += idx
print(mySum)
2500
# 要求:乘法表中所有乘积小于12的数字打印出来
for i in range(1,10):
for j in range(1,10):
n = i*j
if n > 12:
continue
sys.stdout.write(str(n))
sys.stdout.write("\t")
sys.stdout.write("\n")
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12
3 6 9 12
4 8 12
5 10
6 12
7
8
9
函数
- 能完成一定逻辑业务功能的程序块(一堆程序代码),是程序模块的一个单位
- 作用:
- 代码组织
- 代码复用
- 几个函数:
- 函数名/函数定义
- 参数
- 返回值
# 函数定义
def funcName():
print("这是我的第一个函数")
# 函数的调用
# 调用直接用函数的名称,有参数的输入参数,没有用空括号
funcName()
这是我的第一个函数
def funcOne():
for idx in range(1,6):
print(idx)
funcOne()
1
2
3
4
5
函数返回值 return 语句
- 表示无条件结束函数并返回结果
- 约定,任一函数应该都有return 语句表示结束,可以说 return None
# return 例子
# 定义函数,表示两个数相加,则返回相加的和
def getSum(one,two):
return one + two
summ = getSum(33,66)
summ
99
参数
- 在函数中,用来占位具有一定表示意义的变量名
- 分类:
- 形参:形式参数简称
- 实参:实际参数的简称
# 函数参数举例
# 在函数定义的时候,参数没有具体的值,他的主要作用是占据位置
# 我们称之为形参
def func01(name):
print("My name is %s" % name)
func01("wdh")
My name is wdh
关键字参数
- 对参数进行别名设置,同时使参数具有了默认值
- 可以忽略参数的顺序
def func02(name,food):
print(name+" likes eat "+ food)
func02("wdh","apple")
wdh likes eat apple
func02("apple","wdh")
apple likes eat wdh
func02(food="cake",name="wdh")
wdh likes eat cake
### 默认参数
- 参数在定义的时候带默认值
func02("wdh")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-78-dd81ebb8ac58> in <module>
----> 1 func02("wdh")
TypeError: func02() missing 1 required positional argument: 'food'
# 默认参数的定义
# 默认参数需要使用关键字参数,语法格式为arg=xxx
# 默认参数必须放在参数列表后边,且默认参数后不得再有普通参数
# 定义一个函数,函数功能为:显示谁取的了多少成绩
def func03(name,score=60):
if(score>=60):
print("恭喜 %s 考了%d" % (name,score) )
else:
print("遗憾 %s 考了%d" % (name,score) )
func03("wdh")
恭喜 wdh 考了60
func03("wdh",99)
恭喜 wdh 考了99
func03("wdh",12)
遗憾 wdh 考了12
#以下写法错误,一旦用了非default参数不能跟在default参数后面
def func05(arg0=0,arg1=1,arg2=2,arg3):
print(arg0,arg1,arg2,arg3)
File "<ipython-input-87-4e1747f81251>", line 2
def func05(arg0=0,arg1=1,arg2=2,arg3):
^
SyntaxError: non-default argument follows default argument
序列参数,字典参数
- 列表参数:所有参数作为一个列表传入
- 字典参数:参数作为一个字典传入
def myFunc01(a,b,c):
print("This is a example for para")
print("Value of a is %s" % a)
print("Value of a is %s" % b)
print("Value of a is %s" % c)
myFunc01("one","two","three")
This is a example for para
Value of a is one
Value of a is two
Value of a is three
# 把实参作为列表传入
p1 = ["one","two","three"]
# 如果把列表直接传入,则解释器认为你只传入了一个参数
myFunc01(p1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-123-b74647d45fd8> in <module>
2 p1 = ["one","two","three"]
3 # 如果把列表直接传入,则解释器认为你只传入了一个参数
----> 4 myFunc01(p1)
TypeError: myFunc01() missing 2 required positional arguments: 'b' and 'c'
# 如果所有的参数都放入一个列表中,则需要特殊表示出来
# 序列的长度必须与形参个数相同
# 序列位置信息对应相应的参数信息
myFunc01(*p1)
This is a example for para
Value of a is one
Value of a is two
Value of a is three
# 尝试把所有的参数都放入字典中传入
# 字典的长度必须与形参的个数相同
# 字典的键必须对应函数的形参,键作为字符串类型(字典的键和形参的名称必须相同,而排列顺序可以不同)
# 字典的值传递给键对应的参数
d = {"a":"one","b":"two","c":"three"}
myFunc01(**d)
This is a example for para
Value of a is one
Value of a is two
Value of a is three
d1 = {"b":"two","a":"one","c":"three"}
myFunc01(**d1)
This is a example for para
Value of a is one
Value of a is two
Value of a is three
星号元组形参,只需要定义一个*元组形参,则可以传入的参数个数不限制
- 星号元组参数
- 语法:
def 函数名(*元组形参):
语句块
# 定义星号元组参数函数
def func(*arg):
print("进入星号元组函数")
print(arg)
# 如果不输入实参,则函数认为你给了一个空列表
# 如果输入实参,函数自动把实参打包放入列表,然后传入
func()
进入星号元组函数
()
func("wdh")
进入星号元组函数
('wdh',)
func("wdh","wdddd")
进入星号元组函数
('wdh', 'wdddd')
双星号字典参数
- 把传入参数打包成字典传入
- 语法:
def 函数名(**字典形参)
函数体
# 定义一个双星号字典参数函数例子
def func1(**args):
print("进入双星号字典函数参数")
print(args)
func1()
进入双星号字典函数参数
{}
# 双星号字典参数对应的是关键字参数
func1("one","two")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-117-d9b5e354d530> in <module>
1 # 双星号字典参数对应的是关键字参数
----> 2 func1("one","two")
TypeError: func1() takes 0 positional arguments but 2 were given
func1(a="one",b="two")
进入双星号字典函数参数
{'a': 'one', 'b': 'two'}
不定长参数说明:
- 位置形参,星号列表形参,双星号字典形参可以混用
- 如果混合使用,则顺序必须为位置形参,星号列表形参,双星号字典形参
函数返回值
- 返回值一般会有,用return语句返回值
- 函数的类型,一般就是返回值的类型
- 不返回数据可以没有return,不建议去掉
- 如果不返回值,则默认返回None
- 函数可以返回复杂类型,也可以一次返回多个值
# 如果没有return 则也返回None
def func1(one):
print("The first func")
return
func1(999)
The first func
rst = func1(0)
print(rst)
The first func
None
def func2(two):
print("The second func")
rst = func2(33)
print(rst)
The second func
None
def func3(one,two):
three = one + two
print(three)
return three
rst = func3(33,66)
print(rst)
99
99
# 返回多个值的函数
# 多个返回值直接用逗号隔开
def func4(one,two):
one += 100
two += 100
three = one + two
return one,two,three
# 对返回多个值得函数调用
# 如果返回值放入一个变量中,则默认此变量为tuple类型,即多个返回值自动打包成tuple
rst = func4(23,32)
print(rst)
type(rst)
(123, 132, 255)
tuple
o,t,h = func4(23,88)
print(o,t,h)
type(t)
123 188 311
int
# 多个返回值函数接收只能是一个tuple类型或者相同数量的变量列表
one,two = func4(23,88)
print(one,two)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-146-41ea7bf604e7> in <module>
1 # 多个返回值函数接收只能是一个tuple类型或者相同数量的变量列表
----> 2 one,two = func4(23,88)
3 print(one,two)
ValueError: too many values to unpack (expected 2)
函数文档
- 函数文档在函数开头起一定说明性的一段文字
# 函数文档的例子
def func5(one):
'''这是一个函数文档的例子
胜多负少发是电风扇
胜多负少是gfgdf
'''
print("The first func")
return one
func5(1)
The first func
1
# 通过查看__doc__属性可以查看函数定义的doc内容
func5.__doc__ # doc前后都是两个下划线
'这是一个函数文档的例子\n 胜多负少发是电风扇\n 胜多负少是gfgdf\n '
# 函数定义的文档会出现在help函数结果中,供用户查看
help(func5)
Help on function func5 in module __main__:
func5(one)
这是一个函数文档的例子
胜多负少发是电风扇
胜多负少是gfgdf