一、计算圆的面积和周长
PI = 3.1415926
#计算面积函数
def get_area(r):
return PI*r*r
#计算周长函数
def get_primeter(r):
return 2*PI*r
#判断输入函数
def input_r():
while True:
r_str = input("请输入圆的半径:")
try:
r = float(r_str)
return r
except:
print("输入错误")
# 输入圆的半径,算出圆的周长和面积
if __name__ == '__main__':
r = input_r()
print("圆的面积是:%.2f" % get_area(r))
print("圆的周长是:%.2f" % get_primeter(r))
效果展示:
二、输入年份月数计算天数
if __name__ == '__main__':
year= int(input("请输入年份:"))
month= int(input("请输入月份: "))
count_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (month ==2) and (year % 400 ==0 or (year % 4 ==0 and year % 100 != 0)):
print("天数为:%d" % (count_day[month-1]+1))
else:
print("天数为:%d" % int(count_day[month-1]))
这里巧妙的一点就是用了list来优化代码
列表详解:https://www.runoob.com/python3/python3-list.html
效果展示:
三、输入一串字符串判断其中各种类型的个数
if __name__ == '__main__':
str = input("请输入需要判断的字符串:\n")
str_type = {'upper': 0, 'lower': 0, 'digit': 0, 'Chinese': 0, 'other': 0}
for char in str:
if char.isupper():
str_type['upper'] += 1
elif char.islower():
str_type['lower'] +=1
elif char.isdigit():
str_type['digit'] +=1
elif char >= '\u4E00' and char <= '\u9FA5':
str_type['Chinese'] +=1
else:
str_type['other'] +=1
print("大写字母有%d个\n小写字母有%d个\n数字有%d个\n汉字有%d个\n其他类型字符有%d个" % (str_type['upper'], str_type['lower'], str_type['digit'],
str_type['Chinese'], str_type['other']))
这里巧妙的一点就是用到了字典
字典详解:https://www.runoob.com/python3/python3-dictionary.html
效果展示:
四、实现简单的计算器
if __name__ == '__main__':
first_digit = float(input("请输入第一个数字:\n"))
char = input("请输入运算符:\n")
second_digit = float(input("请输入第二个数字:\n"))
if char == '+':
x = first_digit + second_digit
elif char == '-':
x = first_digit - second_digit
elif char == '*':
x = first_digit * second_digit
elif char == '/':
x = first_digit / second_digit
elif char == '%':
x = first_digit % second_digit
else:
print("输入的运算符不合法!")
print("结果:%.2f%s%.2f=%.2f" %(first_digit, char, second_digit, x) )
效果展示: