1.变量
1 1 name='hu qihang' #变量名应为英文,方便阅读 2 2 name_of_gf='chen ye' #多个单词用下划线隔开 3 3 名字='hu qihang' #变量名可以是中文 4 4 NAME='hu qihang' #常量用大写,值是可变的,只是告诉你不要变 5 5 print(name,name_of_gf,名字,NAME,sep='\n')
2.打印
1 sum=''' 2 name='hu qihang' 3 名字='hu qihang' 4 NAME='hu qihang' 5 ''' #三引号可以多行输出,单独使用为注释 6 print(sum)
3.字符串格式化
3.1 %s
1 name=input('your name:') #用户输入input,输入的默认是字符串 2 age=input('your age:') 3 job=input('your job:') 4 info=''' 5 ------info of %s----- 6 Name:%s 7 Age:%s 8 Job:%s 9 '''%(name,name,age,job) #字符串格式化,%s字符串占位符,%d整型占位符,%f浮点型占位符,单一一个%s,可以直接%变量 10 print(info)
3.2 format
3.2.1 format
1 name=input('your name:') 2 age=input('your age:') 3 job=input('your job:') 4 info=''' 5 ------info of {Name}----- 6 Name:{Name} 7 Age:{Age} 8 Job:{Job} 9 '''.format(Name=name,Age=age,Job=job) #可以赋参数也可以不赋,不赋参数的话要按顺序写变量 10 print(info)
3.2.2 format_map
1 info='my name is {name},i am {years} old' 2 print(info.format_map({'name':'huqihang','years':'18'})) #括号里面是字典
4.getpass
1 import getpass 2 3 username=input('your username:') 4 password=getpass.getpass('your password:') #getpass输入时是秘文,在pycharm中不好用, 5 6 print(username,password)
5.条件
5.1 if-else
1 _username='huqihang' 2 _password='123abc' 3 username=input('your username:') 4 password=input('your password:') 5 if username==_username and password==_password: 6 print('welcome user {Name} login!'.format(Name=username)) 7 else: 8 print('invalid username or password!')
5.2 elif
1 age_of_huqihang=23 2 guess_age=int(input('guess age:')) 3 if guess_age==age_of_huqihang: 4 print('yes') 5 elif guess_age>age_of_huqihang: 6 print('smaller') 7 else: 8 print('bigger')
6.循环
6.1 while
6.1.1 三次机会猜数字
1 age_of_huqihang=23 2 count=1 3 while count<4: 4 guess_age=int(input('guess age:')) 5 if guess_age==age_of_huqihang: 6 print('yes') 7 break 8 elif guess_age>age_of_huqihang: 9 print('smaller') 10 else: 11 print('bigger') 12 count=count+1 13 else: 14 print('you have tried too many times!')
6.1.2 任意次机会猜数字
1 age_of_huqihang=23 2 count=1 3 while count<4: 4 guess_age=int(input('guess age:')) 5 if guess_age==age_of_huqihang: 6 print('yes') 7 break 8 elif guess_age>age_of_huqihang: 9 print('smaller') 10 else: 11 print('bigger') 12 count=count+1 13 if count==4: 14 continue_try=input('do you want to guessing.y/n') 15 if continue_try=='y': 16 count=1 17 else: 18 print('lost!')
6.2 for
6.2.1三次机会猜数字
1 age_of_huqihang=23 2 for i in range(3): 3 guess_age=int(input('guess age:')) 4 if guess_age==age_of_huqihang: 5 print('yes') 6 break #结束当前循环。多重循环时,结束当前循环,并不是结束所有循环 7 elif guess_age>age_of_huqihang: 8 print('smaller') 9 else: 10 print('bigger') 11 else: #for循环的else是执行完循环以后就运行else语句,如果break了,就跳出for不执行else 12 print('you have tried too many times!')
6.2.2步长
1 for i in range(0,10,2): #从0到10,不包括10,2是步长,打印一个跳一个,默认是1
2 print(i)
6.3 break和continue
6.3.1 break
1 for i in range(0,10): 2 if i<3: 3 print(i) 4 else: 5 break #结束当前循环 6 print('oops')
6.3.2 continue
1 for i in range(0,10): 2 if i<3: 3 print(i) 4 else: 5 continue #跳出本次循环,继续下次循环 6 print('oops')