Python超好用,要认真学哦!
1、先来简单基础入门(加减乘除)
a,b =map(int,input().split())#输入两个整数(a>b)
c=a+b
print('{0}+{1}={2}'.format(a,b,c))#通过格式化方式({})来选择要输出的变量
c=a-b
print('{0}-{1}={2}'.format(a,b,c))
c=a*b
print('{0}*{1}={2}'.format(a,b,c))
c=round(a/b)#round():四舍五入,不含小数点
print('{0}/{1}={2}'.format(a,b,c))
输出:
2、输入多个数字,求出其中的个数、最小值、最大值
lst=[]#先放一个数组,准备接受数据
lst=input().split()#输入多个数据
print("输入个数有:",len(lst))#求出数组的长数
print("最小值为:",min(lst))#求出数组的最小值
print("最大值为:",max(lst))#数组的最大值
输出:
3、输入一行字符,分4行依次输出其中包含英文字母(不区分大小定)、数字、空格及其它字符的个数。
string=input()#输入一行字符串
alpha=digit=space=other=0#设置字母、数字、空格、其它字符为0
for i in string:
if i.isalpha():#判断是否为字母
alpha+=1
elif i.isdigit():#判断是否为数字
digit+=1
elif i.isspace():#判断是否为空格
space+=1
else:#剩下为其它字符
other+=1
print("字母有{}个".format(alpha))
print("数字有{}个".format(digit))
print("空格有{}个".format(space))
print("其他字符有{}个".format(other))
输出:
4、定义矩形类Rect,打印矩形的长、宽、周长、面积等信息;
class Rect:#定义类Rect
def __init__(self,length,width):#构造方法(创建对象实例时被调用)
#self 代表当前对象,类定义中所有函数的第1个参数必须是self
self.length=length#实例属性(length,width)写在 self 后面
self.width=width
def perometer(self):#定义方法,求周长
return 2*(self.length+self.width)
def area(self):#定义方法,求面积
return self.length*self.width
def show(self):#输出长、宽、周长、面积
print("矩形长:",self.length)
print("矩形宽为:",self.width)
print("矩形周长为:",self.perometer())
print("矩形面积为:",self.area())
r1=Rect(40,30)#创建对象
r1.show()#调用方法
输出: