本文介绍了Python中的字符串,整数和运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在操作中使用算术运算符(用户输入为字符串)?我可以打印操作本身,但我想打印解决方案!

How can I use an arithmetic operator (input by the user as a string) in an operation? I can print the operation itself, but I want to print the solution!

这是我的笨拙尝试:

# Initialise variables

x = 2
y = 3

# Prompt the user for an arithmetic operator

operator = input("Please enter  *,  /,  +,  or  - : ")

# Calculate the operation

result = (str(x) + operator + str(y))

# Display the result

print(result)


推荐答案

使用,其函数执行与算术运算相同的操作。

Use the operator module, which has functions that perform the same operations as your arithmetic operations.

import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}

op = input("Please enter  *,  /,  +,  or  - : ")
result = ops[op](x, y)

这篇关于Python中的字符串,整数和运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:00