1.原始题目类似于(来自B站 “过气网红ALEX”,老师讲的很好,感谢):
注意:a.isdigit() 要加括号【不然会报错】,并在判别类型后才可进行int的转换
本质相同的程序:
while True: # while 循环,实现多次输入判别
a = input("请输入一个数字") #获取键盘输入(默认输入的是字符,不可直接当作数字比大小)
if a.isdigit() is True: #判断键盘输入的是不是整数字符,is True可以去掉
b=eval(a) #或者int也可,将a这个字符确定为正儿八经可以比较大小的数字
if b>10:
print("大胆猜")
elif b<10: #elif 是简写,而且必须这样简写
print("瞎说")
else: #实际这是等于10的情形
print("年龄是{}".format(b))#注意 这种格式 "{}".format()
else:
break #当输入的不是数字时,程序终止退出,否则while循环下可以一直进行
结果展示:
补充:if 后面要加else但是,不一定是非得对其的那种,如下:
#输出1-100的所有素数
for i in range(1,100):
for j in range(2,i-1):
if i%j==0:
break
else:
print(i)
2.判断输入的字母数字空格的个数
#判断输入的字符串中,字母数字下划线的个数
while True:
msg=input(">:").strip()
if not msg:continue
str_count=0
int_count=0
spa_count=0
special_count=0
for i in msg:
if i.isdigit(): #判断输入的内容是不是数字digit
int_count +=1
elif i.isalpha(): #判断输入的内容是不是字母alpha
str_count +=1
elif i.isspace():#判断输入的内容是不是space空格
spa_count +=1
else:
special_count +=1
print(f"str count:{str_count},int count:{int_count},special count:{special_count},space count:{spa_count}")
#注意f":{}"的格式,除了{}内的是变量外,其他的是字符串.多个用英文逗号隔开