3、变量和简单数据类型
-
变量声明规则:
- 变量名只能包含字母、数字、和下划线。变量名可以以字母或者下划线打头,但不能以数字打头,例如可message_1,不1_message;
- 变量名不能包含空格,可以使用下划线分割其中单词,例如可student_name,不 student name(会引发错误);
- 不要将Python关键字和函数名作为变量;
- 变量名应既简短又具有描述性,例如,name比n好,student_name比s_n好;
- 慎用小写字母l和大写字母O,因为它们可能被人看错成1和0。
使用时避免命名错误
message = "Hello python world !" print(mesage)
-
字符串:
在Python中用引号括起来的都是字符串,其中引号可以是单引号,也可以是双引号
例如:"This is a string." 'this is a string.'
1、使用方法修改字符串的大小写
name = 'ada lovelace' #首字母大写 print(name.title()) #全部大写 print(name.upper()) #全部小写 print(name.lower())
2、合并(拼接)字符串
Python使用加号(+)来合并字符串
first_name = "ada" last_name = "lovelace" full_name = first_name + "" + last_name print(full_name)
3、使用制表符或者换行符来添加空白
#未使用换行符 print("Python") #输出结果 Python #使用换行符 print("\tPython") #输出结果 Python
#使用换行符\n
print("Languages:\nPython\nC\nJavascript")
Languages:
Python
C
JavaScript
4、删除空白
rstrip()删除末尾空格
lstrip()删除开头空格
strip()删除两端空格
使用删除命令只是暂时删除,需要把删除后的结果存回变量中
>>>favorite_language = 'python ' >>>favorite_language 'python ' >>>favorite_language.rstrip() 'python' >>>favorite_language 'python '
>>>favorite_language = favorite_language.rstrip()
>>>favorite_language
'python'
>>>favorite_language = ' python '
>>>favorite_language.rstrip()
' python'
>>>favorite_language.lstrip()
'python '
>>>favorite_language.strip()
'python'
5、使用字符串时避免语法错误
例如在使用单引号括起的字符串中,如果包含撇号,就将导致错误
#正确使用方法 message = "One of python's strengs is its diverse community" print(message) One of python's strengs is its diverse community #错误用法 message = 'One of python's strengs is its diverse community' print(message) #你将看到如下输出 File "<stdin>", line 1 message = 'One of python's strengs is its diverse community' ^ SyntaxError: invalid syntax
6、Python2中的print语句
在Python2中,无需将要打印的内容放在括号内,从技术上来说Python3中的print是一个函数,因此括号必不可少
>python2.7 >>>print "Hello Python 2.7 world!" Hello Python 2.7 world!
7、数字
7.1整数
在Pythoy中,可对整数执行加( + )减( - )乘( * )除( / )运算
>>>2+3 5 >>>3-2 1 >>>2*3 6 >>>3/2 1.5 #乘方运算 >>>3 ** 2 9 >>>3 ** 3 27 >>>10 ** 6 1000000 #次序运算 >>> 2 + 3*4 14 >>>(2 + 3) * 4 20
8、使用函数str()避免类型错误
brithday.py
age = 23
>>> message = "Happy" + age + "Birthday!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
print(message)
#正确做法
age = 23
message = "Happy" + str(age) + "Brithday!"
print(message)

浙公网安备 33010602011771号