python入门基础知识1.docx
print("hello world")'hello world'#与上行代码不同之处在于,输出结果会将引号也输出print("hello"" world")print("hello"*3)print('5'+'8')print(5+8)print("hello,worldn"*2) #n:换行转义符print("vicky",end="") #输出vicky后不换行,默认为换行。i=1while i<4: print("wow",end="") i+=1while i<4: print("wow") i+=1#BIF:内置函数:inputintprintteep=input("guess the numeber in xiaoming's heart") #input:括号内即提示字符串在读取输入前打印到标准输出guess=int(teep) #int:将提示字符串变为整数if guess=0: print("good") print("what a pity ! no reward!")else: print("false,it is 0!") print("game over!")a=input("请输入你的姓名:")print("hello , "+a)#用对自身表示转义print("now")#n会自动换行,只输出ow. t表示四个空格一个tabprint("now")#会输出now#用r表示使用原始字符串#在字符串末尾加上反斜杠字符串后加“”;如果字符串中间存在,可以前面加r,后面加print('xx''')#想要输出双引号可以将字符串用单引号扩起来。print('i "love" you')strprint(str)#输出跨越多行的长字符串,如一首诗:在字符串前后加三重引号或者在每句末尾添加换行符n。所见即所得,直接在 console里面输入,在 script里面运行会报错str="""鹅鹅鹅,曲项向天歌。白毛浮绿水,红掌拨清波。"""print(str)del str #删去单个变量help(input)#reset有很多种,所以只运行reset不会有结果,%reset?继续查看运行细节。reset-s #删去namespace,reset in #删去输入记录reset out #删去所有输出记录#运算符优先级:幂运算比左侧优先级高,比右侧优先级低。#幂运算>正负号>算术操作符>比较操作符>逻辑操作符 not>and>orint() #截断处理,不是四舍五入。int(4.99)=4int(float(input("a number: ")+0.5)#将int转化为四舍五入型float()#在不确定字符串表示的数字是否为整数时,可先用float再用intstr()type()x=9.0isinstance(x,int) #判断x是否为整数类型5%3 #求余5*2 #幂5/3 #地板除法,得到的商小数取整-2*5+6*-9 #不加括号也可以,但最好加上 (not 1 )or (0 and 1 )or (3 and 4 )or (5 and 6) or( 6 and 7 and 8)#判断逻辑:a and b :会依次判断完所有部分才结束 c or d:if c为true,就直接结束。#上式0 or 0 or(3 and 4 )or (5 and 6) or( 6 and 7 and 8),然后3 and 4,判断4正确,直接输出。score=int(input("请输入一个分数 :")if 100>=score>=90: print("A")elif 90>score>=80: #elif=else if print("B")elif 80>score>=60: print("C")elif 60>score>=0: print("D")else: print("输入错误")#悬挂else:c语言中,else会与它最近的那个if搭配;而python强制属于同一个缩进的相匹配。#三元操作符:三个操作数。x if (条件) else yx,y=4,5small=x if x<y else y#assert断言:当后面的条件为假时,程序会自动奔溃并显示assertionerror。我们可以在在程序中插入若干检查点,确保只有后面条件为真时程序才正常执行。assert 3>4assert 3<4#循环:whileforrangebreakcontinuemember="vicky"for i in member: print(i,end=" ")name="vicky","mary","linda","bob"for i in name: print(i,len(i)range(5) #类似R里面的seq,range只有一个参数时默认从0开始,在参数前结束,不包含参数。list(range(5)list(range(1,11,2)bingo="you are so beautiful!"answer=input("please input some words :")while True: if answer=bingo: break answer=input("sorry,please input again :")print("good job!")for i in range(10): #对于09,除以2的余数不等于0,直接输出对应数字,进入下一个循环;否则ii2,输出i,进行下一个循环。 if i%2!=0: print(i) continue i+=2 #不影响循环中的i,改成x=x+2,print(x)完全可以。或者直接改为print(i+2) print(i)for i in range(2): print(i) i+=2 print(i)#一个显著的例子:循环体内i的变化并没有影响循环条件中i的值。虽然循环体内i+=2,但是循环条件中的i还是会遍历range中的每一个元素。#模拟摸球所有可能结果:3红,3黄,6蓝,摸八个print('redtyellowtblue')#t:tab,四个空格for red in range(0, 4): for yellow in range(0, 4): for blue in range(2, 7): if red + yellow + blue = 8: print(red, 't', yellow, 't', blue)