01-Python函数「南开大学」

## 1. 实现计算器

1. 重复运行
2. 用户输入 q 则退出程序
3. 获取用户输入
4. 类型转换
``````# -*- 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()
``````

AI悦创原创...大约 2 分钟PythonPython一对一教学Python一对一辅导Python 辅导编程一对一教学少儿编程一对一南开大学南开大学Python辅导PythonPython一对一教学Python一对一辅导Python 辅导编程一对一教学少儿编程一对一南开大学南开大学Python辅导