变量和简单的数据类型
变量和简单的数据类型
在程序中可以随时修改变量的值
1、变量
举例说明:
message = "hello python world"
print(message)
message = "hello python world NO1"
print(message)
输出内容:
hello python world
hello python world NO1
总结:在程序中可以随时修改变量的值,而python智只会记录变量的最新值。
1.1 变量的命名和使用
变量的命名:
1.变量名只能包含字母、数字和下划线;
2.变量名只能以字母和下划线打头,不可以以数字打头;
3.变量名不能包含空格;
4.不要将Python关键字和函数名当做变量名,例如print;
5.变量名应简短且具有描述性。
2、字符串
字符串就是一系列字符,在Python中用单引号或者双引号括起来。
2.1 使用方法修改字符串的大小写
举例说明:
name = "abcdEfg python"
print(name)
adbcEgf
将变量中首字母全部变为大写:
name = "abcdEfg python"
print(name.title())
Abcdefg Python
将变量中全部变为大写:
name = "abcdEfg python"
print(name.upper())
ABCDEFG PYTHON
将变量中全部变为小写:
name = "abcdEfg python"
print(name.lower())
abcdefg python
2.2 合并(拼接)字符串
很多时候,需要将字符串进行合并,例如,需要将姓和名存储在不同的变量中,然后再拼接显示。
举例说明:
frist_name = "zhang"
last_name = "san"
full_name = frist_name+""+last_name
print(full_name)
zhangsan
我们也可以使用变量里的信息来创建完整的信息。
frist_name = "zhang"
last_name = "san"
full_name = frist_name+""+last_name
print("hello, "+full_name.title() +"!")
hello, Zhangsan!
还可以把拼接后的信息存储再变量中,之后再打印出来
frist_name = "zhang"
last_name = "san"
full_name = frist_name+""+last_name
message = "hello, "+full_name.title() +"!"
print(message)
hello, Zhangsan!
2.3 制表符和换行符的使用
制表符和换行符会使得内容更加的易读!
制表符:\t
print("python")
print("\tpython")
python
python
换行符:\n
print( "languages:\npython\nC\nJAVA")
languages:
python
C
JAVA
制表符和换行符可以一起用:
print( "languages:\n\tpython\n\tC\n\tJAVA")
languages:
python
C
JAVA
2.4 删除空白
Python的字符串中无法自动的将空白删除,空白也是当作内容打印出来。但是在Python使用方法去除空白易如反掌。
去除末尾的空白字符:rstrip():
>>> message = ' python '
>>> message
' python '
>>> message.rstrip()
' python'
>>>
当时当你再敲一遍message,又会恢复原样
>>> message = ' python '
>>> message
' python '
>>> message.rstrip()
' python'
>>> message
' python '
>>>
如果需要永久去除,则需要将结果再次赋值给变量
>>> message = ' python '
>>> message
' python '
>>> message = message.rstrip()
>>> message
' python'
>>> message
' python'
>>> message
' python'
>>>
去除开头的空白
>>> message = ' python '
>>> message = message.lstrip()
>>> message
'python '
去除两端的空白
>>> message = ' python '
>>> message = message.strip()
>>> message
'python'
3.数字
3.1 整数
在Python中,可对加减乘除直接运算
>>> 3+2
5
>>> 3-1
2
>>> 3*5
15
>>> 6/2
3.0
使用两个乘号则表示乘方。
>>> 3**2
9
>>> 2**6
64
Python还支持运算次序。
>>> 3+2*5
13
>>> (6+8)*2
28
3.2 浮点数
一般情况下,Python可以很好的处理浮点数的运算。
>>> 0.1+0.1
0.2
>>> 2*0.1
0.2
>>>
但是结果包含的小数位数可能是不确定的:
>>> 0.2+0.1
0.30000000000000004
>>> 0.2*0.1
0.020000000000000004
3.3 使用函数str()避免类型错误
例如:
age = 23
print("Happy "+age+"rd Brithday!")
Traceback (most recent call last):
File "/home/sbz/python_works/pinjie.py", line 2, in <module>
print("Happy "+age+"rd Brithday!")
TypeError: can only concatenate str (not "int") to str
此处报了一个错,原因是打印信息里面有个int类型的数值,但是Python不知道该如何去解答他,所以会报错;
我们可以使用str()将其以字符串打印出来
age = 23
print("Happy "+str(age)+"rd Brithday!")
Happy 23rd Brithday!