第一个程序
1 print("hello world")
变量 name
1 name = "Li Haitao" 2 name2 = name 3 print("My name is",name,name2) 4 name = "Zhao jincgen" 5 print(name,name2)
结果:
每个变量有自己的地址。
for循环
1 for i in range(0,10,2): 2 if i < 5: 3 print("第",i) 4 else: 5 continue 6 print("呵呵...")
结果:
continue跳出本次循环(自己最近的一个循环)
break 跳出循环(自己最近的一个循环)
while循环
1 count = 0 2 while True: 3 print("count:",count) 4 count = count+1 5 if count == 1000: 6 break
结果:
猜年龄小游戏
1 age_of_lihaitao = 24 2 count = 0 3 4 while count<3: 5 guess_age = int(input("年龄是:")) 6 if guess_age == age_of_lihaitao: 7 print("恭喜你!猜对了") 8 break 9 elif guess_age > age_of_lihaitao: 10 print("猜大了") 11 else: 12 print("小了") 13 print("剩余次数",2-count) 14 count +=1 15 if count == 3: 16 countine_confirm = input("是否要继续猜:") 17 if countine_confirm != "n": 18 count = 0
I/O
1 # Author:Li 2 3 username = input("username:") 4 5 password = input("password:") 6 7 age = int(input("age:")) 8 #强制类型转换 9 info1 = '''d 10 -------info1 of %s------- 11 username:%s 12 password:%s 13 age:%d 14 ''' %(username,username,password,age) 15 # %d为整数型 %为字符串 16 print(info1) 17 18 19 info2 = '''d 20 -------info2 of {_username}------- 21 username:{_username} 22 password:{_password} 23 age:{_age} 24 ''' .format(_username=username, 25 _password=password, 26 _age=age) 27 # %d为整数型 %为字符串 28 print(info2) 29 30 31 info3 = '''d 32 -------info3 of {0}------- 33 username:{0} 34 password:{1} 35 age:{2} 36 ''' .format(username,password,age) 37 # %d为整数型 %为字符串 38 print(info3)
结果:
作业
登录,账户密码储存在文件中,限制登录
1 count = 0 2 3 for i in range(3): 4 b = input("账号:") 5 c = b + "," + input("密码:")+"\n" 6 7 passwd_f = open('D:\python\password_f.txt', 'r') 8 text = passwd_f.readlines() 9 for j in range(len(text)): 10 if text[j] == b + "\n": 11 print("----账号已经被锁定----") 12 exit() 13 14 passwd = open('D:\python\password.txt', 'r') 15 text = passwd.readlines() 16 for h in range(len(text)): 17 if text[h] == c: 18 print("------欢迎你------") 19 exit() 20 21 print("--密码或账户错误--") 22 passwd.close() 23 else: 24 print("--账户已经被锁定--") 25 passwd_f = open('D:\python\password_f.txt', 'a') 26 passwd_f.write(b + "\n") 27 passwd_f.close() 28 #username = input("账号:") 29 #password = input("密码:")