一、Hello World!
1 print("Hello World!")
二、变量
1.变量声明
1 name = "Andy Lau"
上述语句即是一次变量声明,将内容”Andy Lau“赋值给变量"name"
2.变量定义规则
- 变量名只能是 字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字
- 以下关键字不能声明为变量名
[‘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‘]
3.变量的赋值
1 name = "Alex Li" 2 3 name2 = name 4 print(name,name2) 5 6 name = "Jack"
三、用户输入
1 name = input("What is your name?") 2 print("Hello ",name )
输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:
import getpass # 将用户输入的内容赋值给 name 变量 pwd = getpass.getpass("请输入密码:") # 打印输入的内容 print(pwd)
四、表达式 if......else
场景一、用户登陆验证
1 _username =‘alex‘ 2 _password =‘123abc‘ 3 4 username=input("username:") 5 password=input("password:") 6 7 if username==_username and password==_password : 8 print("yes,welcome") 9 else: 10 print("error")
场景二、猜年龄游戏
在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 28 6 7 user_input = int(input("input your guess num:")) 8 9 if user_input == my_age: 10 print("Congratulations, you got it !") 11 elif user_input < my_age: 12 print("Oops,think bigger!") 13 else: 14 print("think smaller!")
五、表达式for loop
最简单的循环10次
1 for i in range(0,10): 2 print("loop:", i )
输出
1 loop: 0 2 loop: 1 3 loop: 2 4 loop: 3 5 loop: 4 6 loop: 5 7 loop: 6 8 loop: 7 9 loop: 8 10 loop: 9
需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
1 for i in range(0,10): 2 if i<5: 3 continue #不往下走了,直接进入下一次loop 4 print("loop:", i )
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
1 for i in range(0,10): 2 if i>5: 3 break #不往下走了,直接跳出整个loop 4 print("loop:", i )
六、while loop
while循环的结构
1 while 条件: 2 循环体
死循环:一直循环不停
1 count = 0 2 while True: 3 print("你是风儿我是沙,缠缠绵绵到天涯...",count) 4 count +=1
while循环示例
1 count = 0 2 while True: 3 print("你是风儿我是沙,缠缠绵绵到天涯...",count) 4 count +=1 5 if count == 100: 6 print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼的臭男人..") 7 break
场景一、猜年龄
如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序
1 age_of_oldboy = 56 2 count=0 3 while count<3: 4 guess_age = int(input("guess_age:")) 5 if age_of_oldboy == guess_age : 6 print("yes,you got it") 7 break 8 elif guess_age>age_of_oldboy : 9 print("think smaller") 10 else: 11 print("think bigger") 12 count+=1 13 else:print("fuck off")
场景二、任性猜年龄
1 age_of_oldboy = 56 2 count=0 3 while count<3: 4 guess_age = int(input("guess_age:")) 5 if age_of_oldboy == guess_age : 6 print("yes,you got it") 7 break 8 elif guess_age>age_of_oldboy : 9 print("think smaller") 10 else: 11 print("think bigger") 12 count+=1 13 if count ==3: 14 continu_confirm = input("do you want to continue? ") 15 if(continu_confirm != ‘n‘): 16 count=0;