1. 实现计算器
要求:
- 重复运行
- 用户输入 q 则退出程序
- 获取用户输入
- 类型转换
# -*- coding: utf-8 -*-
# @Time : 2023/1/27 19:06
# @Author : AI悦创
# @FileName: hw01.py
# @Software: PyCharm
# @Blog :https://bornforthis.cn/
# 计算器✅
# 重复执行
# 判断退出
# 获取用户输入✅
# 类型转换✅
def calculator(num1, num2, operation):
"""
:param num1: int
:param num2: int
:param operation:
:return: int or str
"""
if operation == "+":
return num1 + num2
elif operation == "-":
return num1 - num2
elif operation == "/":
return num1 / num2
elif operation == "*":
return num1 * num2
else:
return "Operation Error......"
def str_to_int_or_float(target):
if target.count(".") == 1:
return float(target)
else:
return int(target)
def main():
while True:
print("""请输入计算数据,输入格式:num1,num2,运算符""")
userinput = input(":>>>").split(",")
if len(userinput) == 1 and userinput[0].lower() == 'q':
break
num1, num2, operation = userinput
# result = calculator(int(num1), int(num2), operation)
result = calculator(str_to_int_or_float(num1), str_to_int_or_float(num2), operation)
print(result)
# num1, num2, operation
# if __name__ == '__main__':
# main()
main()
原创2023年1月28日...大约 2 分钟