Python基础
# encoding: utf-8
#第一个python程序
print('hello world')
'''
这是多行注释,请用三个引号
注释
注释
注释
注释
注释
注释
注释
注释
'''
#单行注释
#单行注释
if (5>3): print('shiduide')
#变量名称区分大小写
x=10 y='tom' print(x) print(y)
#向多个变量赋值
x,y,z='aaa','bbb','ccc' print(x) print(y) print(z)
x=y=z='多变量赋值的第二种方式'
print(x) print(y) print(z) x=3 y=4 print(x+y)
#全局变量:在函数外部创建的变量为全局变量
x='wwww' def myfunction(): print('我司'+x) myfunction()
#global关键字:通常,在函数内部创建变量时,该变量为局部变量,只能在该函数内部使用。
#要在函数内部创建全局变量,可以用关键字:global
def myfunction(): global x x='在函数内部的全局变量' print('这是'+x) myfunction()
#另外,如果在函数内部更改全局变量的值,请使用global关键字引用该变量
x='全局变量的值' def myfunction(): global x x='修改后的全局变量的值' print(x) myfunction()
#获取变量的数据类型:type()函
x=8 y=6.3 print(type(x)) print(type(y))
#数据类型转换:可以使用int(),float()方法从一种类型转换为另一种类型
x=10 y=6.3 a=float(x) b=int(y) print(type(a)) print(type(b))
#python没有random()函数来创建随机数,但是python有一个名为random的内置模块,可用于生成随机数
#例如:导入random模块,并显示1-10之间的随机数
import random print(random.randrange(1,10))
#给变量赋值多行字符串:用三个单引号或双引号
a='''adsfgfadgfg afgfgsdfdgsfg sdg''' print(a)
#字符串是数组:获取位置1处的字符(第一个字符的位置为0)
#一个空格占一个字符
a='hello world' print(a[1]) #获取位置2的字符:e print(a[2:7]) #获取从位置2到位置7(不包括)的字符:llo w print(a[-5:-2]) print(len(a)) #获取字符串长度
#strip()方法可以删除开头和结尾的空白字符
a=' Hello World ' print(a.strip()) print(a.lower()) #lower返回小写的字符串,把大写的转成小写 print(a.upper()) #转成大写 print(a.replace('ell','tttt')) print(a.split(',')) #从,处分割字符串
#检查字符串
txt='hello world' x='wor' in txt y='wor' not in txt print(x) print(y)
#字符串串联
a='hello' b='world' c=a+b d=a+','+b print(c) print(d
#字符和数字串联:format() 方法接受不限数量的参数,并放在各自的占位符中.您可以使用索引号 {0} 来确保参数被放在正确的占位符中
qty=5 item=999 price=24.5 myorder='i want to pay {2} dollars for {0} pieces of item {1}' print(myorder.format(qty,item,price))
#布尔值
print(5>3) print(5<3) print(5==5)
#当在 if 语句中运行条件时,Python 返回 True 或 False:
a=200 b=30 if b>a: print('b比a大') else: print ('b比a小')
#Python 编程语言中有四种集合数据类型:
#列表(List)是一种有序和可更改的集合。允许重复的成员。
#元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
#集合(Set)是一个无序和无索引的集合。没有重复的成员。
#词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。
#元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
#集合(Set)是一个无序和无索引的集合。没有重复的成员。
#词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。
#列表
thislist=['apple','banana','cherry'] print(thislist[1]) #打印第二项 print(thislist[-1]) #打印最后一项 print(thislist[2:5]) #打印3,4,5项
#修改特定项目的值,使用索引号
thislist[1]='mango' print(thislist)
#用for循环遍历列表项:
thislist=['apple','banana','cherry'] for x in thislist: print(x) if 'apple' in thislist: print('apple is in the thislist')
-----列表

浙公网安备 33010602011771号