Day1 python基础1
一、Hello World
print("Hello World!")
二、变量以及字符编码
变量名只能是字母,数字,下划线,且第一个不能是数字
以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
1 name = "Zhang wb" 2 name2 = name 3 print("my name is",name,name2) 4 5 name = "Sha Shan" 6 gf_of_oldboy = "Rlongyi" 7 8 PIE = "常量" 9 10 print(name,name2)
ASCII 255 1B,GB2312 7XXX汉字,GBK 2xxxx汉字,GB18030 27000汉字 向下兼容
Unicode万国码 2B
UTF-8可变长,英文-ascii 1B,中文-utf8 3B
三、注释
单行注释 #注释内容
多行注释 ‘’‘注释内容’‘’或“”“注释内容”“”
四、输入
1 username=input("username:") 2 password=input("password:") 3 print(username,password)
需注意input的结果是字符串
输入密码时不可见,可利用getpass
1 import getpass 2 #pycharm不好用 3 password = getpass.getpass("password:")
不同形式的输入
1 name=input("name:") 2 age=int(input("age:")) 3 job=input("job:") 4 info = ''' 5 --------- info of %s ---- 6 Name:%s 7 Age:%d 8 Job:%s 9 '''%(name,name,age,job) 10 print(info)
%s 字符串,%d,整数,%f,浮点数
1 name=input("name:") 2 age=int(input("age:")) 3 job=input("job:") 4 info2 = ''' 5 --------- info of {_name}---- 6 Name:{_name} 7 Age:{_age} 8 Job:{_job} 9 '''.format(_name=name,_age=age,_job=job) 10 print(info2)
name=input("name:") age=int(input("age:")) job=input("job:") info3 = ''' --------- info of {0}---- Name:{0} Age:{1} Job:{2} '''.format(name,age,job) print(info3)
五、if...else...
猜年龄
1 age = 56 2 3 guess_age = int(input("guess age:")) 4 5 if guess_age == age : 6 print("yes,you get it") 7 elif guess_age > age : 8 print("think smaller...") 9 else: 10 print("thinker bigger...")
六、while
while死循环
1 count = 0 2 while True: 3 print("count:",count) 4 count+=1
利用while实现只有三次机会的猜年龄
1 count = 0 2 while count < 3: 3 guess_age = int(input("guess age:")) 4 if guess_age == age: 5 print("yes,you get it") 6 break 7 elif guess_age > age: 8 print("think smaller...") 9 else: 10 print("thinker bigger...") 11 count+=1 12 else: 13 print("you have tried too many times...") 14 #循环正常走完,执行else,break的话不执行else
七、for
利用for输出0--9
1 for i in range(10): 2 print("loop",i) 3 print("")
利用for输出5到9的奇数
1 for i in range(5,10,2): 2 print("loop", i)
利用for实现只有三次机会的猜年龄
1 age = 56 2 3 for count in range(3): 4 guess_age = int(input("guess age:")) 5 if guess_age == age: 6 print("yes,you get it") 7 break 8 elif guess_age > age: 9 print("think smaller...") 10 else: 11 print("thinker bigger...") 12 13 else: 14 print("you have tried too many times...")
猜年龄任意玩
age = 56 count = 0 while count < 3 : guess_age = int(input("guess age:")) if guess_age == age: print("yes,you get it") break elif guess_age > age: print("think smaller...") # print(count) else: print("thinker bigger...") count+=1 if count == 3: countinue_confirm = input("do you want to keep guessing..?(y/n)") if countinue_confirm != 'n' : count = 0