任何语言的学习都是从打印hello world开始的,学习Python可以不意外。
print("hello world")
1、变量
Python的变量不需要指定类型,根绝初始化值的类型来确定变量的类型,可以通过type()函数测试变量的类型
a = "hello world"
printf(type(a))
b = 2017
printf(type(b))
2、输入和输出
-
格式化输出:Python的格式化输出和C语音有些类似,不同的地方是,格式字符串后面接%,如果是多个变量,需要用括号括起来。
print("%s,%s"%("Hello", "world"))
输入:市面主要的Python版本是Python2和Python3,这里面有个坑,input函数在输入字符串时Python2和Python3是相同的,但输入数字的时候,Python2会处理成数字,而Python3会当成字符串处理,Python2的raw_input和Python3的input是相同的
3、条件语句写法:
if condition1:
print("condition1")
elif condition2 and condition3:
print("condition2 and condition3")
elif condition4 or condition5:
print("condition4 or condition5")
else:
print("都不满足条件")
4、循环语句写法
while condition:
if condition1:
break
if condition2:
continue
for item in array :
print(item)
5、综合练习-两个变量交换
def swap(a, b)
a, b = b, a
6、综合练习-猜拳游戏
#!/usr/local/bin/python3
import random
print("欢迎参加猜拳游戏")
while True:
num = input("请输入一个数字:1、石头;2、剪刀;3、布\n0、退出游戏\n")
if num == "0":
break
if num != "1" and num != "2" and num != "3":
print("输入错误")
continue
computer = str(random.randint(1,3))
if (num == "1" and computer == "2") or (num == "2" and computer == "3") or (num == "3" and computer == "1"):
print("恭喜您赢了")
elif num == computer:
print("平局")
else:
print("再接再厉")
7、综合练习-学生成绩查询系统
#!/usr/local/bin/python3
#全局变量,如果是可变的,在修改的时候,可以不用加global,当如果是不可变的,在修改的时候,必须加上global
#全局学生成绩数据字典
gradeDic = {}
def printWelcom():
"打印欢迎界面"
print("="*50)
print("=============欢迎进入学生成绩系统=========")
print("1、进入成绩录入:")
print("2、进入成绩查询:")
print("0、退出系统")
print("="*50)
def checkGrade(grade):
"判断输入的成绩是否有效"
gradet = 1
if grade.isdigit():
num = int(grade)
if num < 0 or num > 100:
print("请输入一个0-100的数字")
return False
return True
else:
print("请正确输入成绩(0-100)")
return False
def checkYseOrNo(inputMessage):
"判断输入的操作是否为Y和N"
while True:
opt = input("%s"%inputMessage)
if opt == "Y" or opt == "y":
return True
elif opt == "N" or opt == "n":
return False
else:
print("输入错误")
def insterGrade():
"录入学生成绩"
name = ""
math = ""
chinese = ""
english = ""
while True:
name = input("请输入学生姓名:")
while True:
grade = input("请输入数学成绩(0-100):")
isOK = checkGrade(grade);
if isOK:
math = grade
break
while True:
grade = input("请输入语文成绩(0-100):")
isOK = checkGrade(grade);
if isOK:
chinese = grade
break
while True:
grade = input("请输入英语成绩(0-100):")
isOK = checkGrade(grade)
if isOK:
english = grade
break
print("%s的数学成绩:%s;语文成绩:%s;英语成绩:%s"%(name,math,chinese,english)
while True:
opt = checkYseOrNo("是否插入?(Y/N):")
if opt:
user = {"数学":math, "语文":chinese, "英语":english}
gradeDic[name] = user
break
else:
break
opt = checkYseOrNo("是否继续录入学生成绩?(Y/N):")
if opt:
continue
else:
break
def queryGrade():
"查询学生成绩"
while True:
name = input("请输入学生姓名:(输入0退出):")
if name == "0":
break
else:
res = gradeDic.get(name, "没有该学生成绩信息")
print(res)
while True:
printWelcom()
opt = input("请输入一个选项:")
if opt == "0":
break
elif opt == "1":
insterGrade()
elif opt == "2":
queryGrade()
else:
print("输入选项错误,请重新输入。")
以上代码可以在GitHub找到。