Python 学习笔记

Python的变量
 
注意:变量不用指定类型,但是必须初始化。
 
一、变量的使用
1.变量名只能包含字母数字下划线。不能以数字开头。例如:3variable 是错误的。
 
2.变量名不能包含空格,但是可以用下划线隔开。例如:greeting_message可行,但是变量名greeting message是错误的。
 
3.不能将Python中的关键字和函数名作为变量名,即不用使用Python保留用于特殊用途的单词作为变量名。例如:print。
 
4.变量名应该简短又具有描述性。例如:用name就比用n好,用student_name就比sn好。
 
注意:Python的变量名尽量用小写字母来标识,Python是区分大小写的编程语言。
 
 
二、字符串
 
Python中用引号括起的都是字符串。引号可以是单引号或者双引号。
 
例如:
'I like Python' = "I like Python"
 
2.1 字符串函数
 
name = 'hand tech'
print(name.title())
 
>> Hand Tech
方法:title() 以首字母大小的方式显示每个单词。
 
print(name.upper())
>>HAND TECH
print(name.lower())
>> hand tech
 
方法:upper() 以大小方式显示字符串,lower() 以小写方式显示一个字符串
 
去除左右字符串空格的函数: lstrip() ,rstrip()
 
2.2 合并(拼接)字符串
 
Python中合并两个字符串的方式和Java类似都是用 加号(+)来实现的。
 
例如:
print('This is my' + ' first Python program!')
>> This is my first Python program!
 
合并字符串的时候注意必须在”+“两侧的变量必须都是字符或者字符串类型,否则报错。
 
例如:
 
print('hello' + 2 + ' world')
 
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    print('hello' + 2 + ' world')
TypeError: must be str, not int
>>
 
这里可以这样转换:
print('hello ' + str(2) + ' world')
>>hello 2 world
 
将”2“转换成字符串类型即可。
 
2.3 制表符
 
 写一个Tab的
 换行
 回车
 
例如:
>>> print("	Python")
     Python
 
>>> print("Language:
	Python
	C
	JavaScript")
Language:
    Python
    C
    JavaScript
 
2.4 删除空白
>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '

方法:rstrip() 删除字符串右边空格

扩展:lstrip() 删除字符串左边空格,strip() 删除字符串两边空格
 
2.5 正确使用字符串的引号
 
在使用字符串引号时注意单引号的引用。
 
message = 'One of python's strengths is its diverse community.'
print(message)
 
以上单引号引用就是常见的错误。
 
三、数字
 
3.1 整数
 
Python 中两个乘号表示乘方运:
>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000
 
3.2 浮点数
 
Python中将带小数点的数字都称为 浮点数
 
注:任何对浮点数的 加减乘除得到的都是浮点数。
 
 
3.3 数字类型的转换
 
例如:
age = 23
message = "Happy " + age + " rd Birthday!"
print(message)
 
此代码打印执行之后必然会报错误(TypeError: Can't convert 'int' object to str implicitly)
因为字符串类型两边必须是字符串。要想不报错,必须用到类似强制转换的函数 str() 将数字类型转换为字符串类型
mesasge = "Happy " + str(age) + " rd Birthday!"
 
四、注释
 
Python中是以 ”#“ 作为注释标识的。良好的注释是每个优秀程序员必须具备的能力。
 
原文地址:https://www.cnblogs.com/objmodel/p/7655256.html