#pyg001.py
name =" 林小明"
eng = 86
math =93
print(name,"平均成绩:%f",(eng+math)/2)
name = input("请输入姓名:")
age = int(input("年龄:"))
print(name,"年龄:",age)
#pyg002.py
class Student: # 类名大写
__name = "" # 私有实例变量前必须有两个下划线
def __init__(self, name):
self.__name = name # self相当于Java中的this
def getName(self): # 方法名首字母小写,其后每个单词的首字母大写
return self.__name
if __name__ == "__main__":
name1 = input("请输入姓名: ")
student = Student(name1) # 对象名小写
print(student.getName())
#pyg003.py
#函数中的命名规则
import random
def compareNum(num1, num2):
if(num1 > num2):
return 1
elif(num1 == num2):
return 0
else:
return -1
num1 = random.randrange(1, 9)
num2 = random.randrange(1, 9)
print ( "随机产生两个范围在1~9的数:num1 、num2,并输出它们比较大小的结果,若第1个数大,则输出1;若相等则输出0,否则输出-1")
print( "num1 =", num1)
print ("num2 =", num2)
print (compareNum(num1, num2))
#练习:改写上面pyg003.py程序,随机产生两个范围在1~100的数。
#pyg004.py
class A:
def funX(self):
print( "funX()")
def funY(self):
print ("funY()")
if __name__ == "__main__":
a = A()
a.funX()
a.funY()
# pyg005.py
# 规范的变量命名
sumPay = 0 # 年薪
bonusOfYear = 10000 # 年终奖金
monthPay = 6800 # 月薪
sumPay = bonusOfYear + 12 * monthPay # 年薪 = 年终奖金 + 12 * 月薪
# py006.py 在文件的开头定义全局变量
_a = 1
_b = 2
def add():
global _a
_a = 3
return "_a + _b =", _a + _b
def sub():
global _b
_b = 8
return "_a - _b =", _a - _b
print (add())
print( sub())
运行输出结果:
('_a + _b =', 5)
('_a - _b =', -5)
# py007.py 三引号制作doc文档
class Hello:
'''HX hello class'''
def printHello():
'''HX print hello world'''
print ("hello world!")
print( Hello.__doc__)
print (Hello.printHello.__doc__)
Hello.printHello()
运行输出结果:
HX hello class
HX print hello world
hello world!