python编程基础(2)
1.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
def DS(target):
alpha_num = 0
digit_num = 0
blank_num = 0
other_num = 0
for i in target:
if i.isalpha():
alpha_num += 1
elif i.isdigit():
digit_num += 1
elif i.isspace():
blank_num += 1
else:
other_num += 1
return alpha_num,digit_num,blank_num,other_num
t=input("Input a string:")
alpha_n,digit_n,blank_n,other_n=DS(t)
print('alphaNum=%d,digitNum=%d,blankNum=%d,otherNum=%d'%(alpha_n,digit_n,blank_n,other_n))
2.通过定义函数的方式交换两个数的值。
def change(a,b):
a,b=b,a
return (a,b)
3.使用lambda匿名函数求两个数中最大者。
MAX=lambda x1,x2:(x1>x2)*x1+(x1<x2)*x2#三目运算
a=int(input(""))
b=int(input(""))
c=MAX(a,b)
print(c)
4.采用面向对象技术实现两数相加。
class SUM_num():
a=0
b=0
def __init__(self,a,b):
self.a=a
self.b=b
def add_ab(self):
c=self.a+self.b
return c
a=3
b=9
x=SUM_num(a,b)
print(x.add_ab())
5.将小写字符串转换成大写,然后输出到磁盘文件中保存(提示:upper()可转字母为大写)。
s=input("Input a string:")
s1=s.upper()
file=open("new.txt","w")
file.write(s1)
file.close()
总结:
面向对象我一开始以为是使用方法还有类之类的,但是老师使用类
面向对象是使用类吗?/苦恼极了/QAQ
关键语句要突出出来,不要放在输出语句中。这样便于以后调试。