Python基础知识
1、简单的python程序
简单的python程序
`message = 'hello,world' #python 与其他软件不同,不需要在结尾以分号结尾
print(message) #python属于弱类型,即赋给变量什么值,该变量就是什么类型
2、变量的命名和使用
变量的命名和使用
(1)变量名只能包含字母、数字和下划线。变量名可以以字母或下划线打头,但是不可以以数字打头。例如,1_work不可以命名。
(2)变量名不可以包含空格,但是可以以下划线表示空格。
(3)不要将python关键字和函数名用作变量名。`
(4)变量名应简短又具有描述性。
(5)慎用小写字母I和大写O。
import keyword #查关键词
import builtins #查内置函数
注:python无内置常量,可用全大写指出应将某个变量视为常量。
import math
Pi = math.pi
print(Pi) #调用math库里的常量pi
3、字符串
(1) 字符串的创建可用 ’ ,“,“‘。
str1 = ' '
str2 = str() #两种方法用来创建空字符串
str3 = 'name'
print(str3.title()) #以首字母大写显示每一个单词。 注:每一个
print(str3.upper()) #全大写
print(str3.lower()) #全小写
(2)字符串的拼接
first_name = 'Wu'
last_name = "pangpang"
full_name = first_name + " " + last_name
print(full_name)
字符串的拼接需要用加号来合并字符串。
结果
Wu pangpang
(3)空白的添加和删除
添加空白:
>>> print('wu pangpang')
wu pangpang
>>> print('\twu pangpang') #加制表符(\t)来表示2空格
wu pangpang
print("Wu \nyou \nare \nthe most beautiful woman") #添加换行符(\n)
Wu
you
are
the most beautiful woman
删除空白:
>>> n = ' Wu pangpang '
>>> n
' Wu pangpang '
>>> n. rstrip() #去末尾空白
' Wu pangpang'
>>> n.lstrip() #去开头空白
'Wu pangpang '
>>> n.strip() #去两边空白
'Wu pangpang'
4、数字
(1)python使用**表示乘方,且算式开头不能有空格。
(2)带小数点的数字为浮点数。运算中,无须定义浮点数,但是使用有一个浮点数,其结果就是浮点数。注:结果包含的小数位数是不确定的。(3)当需要使用数字的时候,python可能无法识别数字。
> >>> age = 22
> >>> message = 'Happy' + age + 'rd Birthday' Traceback (most recent call last): File "<pyshell#16>", line 1, in <module>
> message = 'Happy' + age + 'rd Birthday' TypeError: can only concatenate str (not "int") to str
可使用str()函数,将python中的非字符串值转换为字符串。
>>> age = 22
>>> message = 'Happy ' + str(age) + ' rd Birthday'
>>> print(message)
Happy 22 rd Birthday
5、注释
(1)单行注释 #
(2)多行注释 ‘’’’’’ 或 “”""""