简体   繁体   English

如何使用户输入不是字符串或输入而是运算符?

[英]How do I make user input not a string or input but an operator?

I was trying to make a quick little user-input calculator but to do that I need the user to decide what operator to use.我试图制作一个快速的小型用户输入计算器,但要做到这一点,我需要用户决定使用什么运算符。 I tried to make the user-input for the operator a string but that obviously didn't work.我试图使操作员的用户输入成为字符串,但这显然不起作用。 I tried it as an integer too but still had no luck.我也尝试将其作为整数,但仍然没有运气。 So I'm confused about what it is that I'm supposed to do.所以我对我应该做什么感到困惑。

so far I only have this and it shows an error:到目前为止,我只有这个,它显示一个错误:

num1 = int(input("What is your first number?: "))
num2 = int(input("What is your second number?: "))
op = (input("Enter an operator: ")
print(num1 + op + num2)

SOLVED解决了

The cleanest safe way to do this is by storing the operators as functions in a dictionary:最干净安全的方法是将运算符作为函数存储在字典中:

from operator import *
num1 = int(input("What is your first number?: "))
num2 = int(input("What is your second number?: "))
op = input("Enter an operator: ")

ops = {
    "+": add, # from the operators module
    "-": sub,
    "/": div,
    "*": mul
}
      
print(ops[op](num1,num2))

you could create some if statements like this:你可以创建一些这样的 if 语句:

if op == '+':
    print(num1 + num2)
if op == '-':
    print(num1 - num2)

Just do the same thing for multiplying and dividing只需对乘法和除法做同样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM