python 基础
1.第一个python程序
print("Hello World")
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']
变量的赋值
name="name" _name="name"
3.字符编码
#_*_coding:utf-8_*_
4.字符编码的区别与介绍
当行注视:# 被注释内容
多行注释:""" 被注释内容 """
name = input("name:") #raw_input 2.x input 3.x #input 2.x = age = int(input("age:") ) #integer print(type(age) , type( str(age) )) job = input("job:") salary = input("salary:") info = ''' -------- info of %s ----- Name:%s Age:%d Job:%s Salary:%s ''' % (name,name,age,job,salary) info2 = ''' -------- info of {_name} ----- Name:{_name} Age:{_age} Job:{_job} Salary:{_salary} '''.format(_name=name, _age=age, _job=job, _salary=salary) info3 = ''' -------- info of {0} ----- Name:{0} Age:{1} Job:{2} Salary:{3} '''.format(name,age,job,salary) print(info3)
5.用户交互程序
#!/usr/bin/env python #_*_coding:utf-8_*_ #name = raw_input("What is your name?") #only on python 2.x name = input("What is your name?") print("Hello " + name )
输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:
#!/usr/bin/env python # -*- coding: utf-8 -*- import getpass # 将用户输入的内容赋值给 name 变量 pwd = getpass.getpass("请输入密码:") # 打印输入的内容 print(pwd)
6.if else流程判断
age_of_oldboy =56 if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!")
7.while 循环
age_of_oldboy = 56 count = 0 while count <3: guess_age = int(input("guess age:") ) if guess_age == age_of_oldboy : print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("think bigger!") count +=1 if count == 3: countine_confirm = input("do you want to keep guessing..?") if countine_confirm != 'n': count =0 #else: # print("you have tried too many times..fuck off")
8.for 循环
for i in range(10): print('----------',i) for j in range(10): print(j) if j >5: break
9.作业,登录判断 输入用户名和密码 认证成功显示欢迎登录 输错三次锁定
#!/usr/bin/env python #-*- coding:utf-8 -*- import getpass import sys count = 0 filePath = "test.txt" while count < 3: userName = input("input you username:") #passWord=getpass.getpass("input you password:") passWord = input("input you password:") file = open(filePath, "r") for line in file: if line.strip() == userName: print("This username is lock") sys.exit() file.close() if userName == "test" and passWord == "123456": print("Welcome login system!") break else: print("username or password is wrong") count += 1 else: file = open(filePath, "a+") file.write(userName) file.write("\n") file.close() print("check your username and password...")