一行三变量

时间:2019-02-10 00:35:26

标签: python

我在这里只是想用python创建一个简单的计算器,我想知道在命令运行时是否有可能将前3行变成一行。我的意思是;我不必按Enter键来输入下一个数字/运算符,而只需按空格键(在输入部分)。

created() {
pipedrive.getAllDeals()
.then(response => {
  // JSON responses are automatically parsed.
  this.posts = response.data
})
.catch(e => {
  this.errors.push(e)
})

// async / await version (created() becomes async created())
//
// try {
//   const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
//   this.posts = response.data
// } catch (e) {
//   this.errors.push(e)
// }

2 个答案:

答案 0 :(得分:8)

您可以使用Python字符串的split方法来完成此操作。请注意,此代码取决于输入的三个对象,这些对象之间用空格隔开。如果输入的数量更多或更少,或者忘记了空格,或者“数字”实际上不是整数,则会出现错误。

print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)

答案 1 :(得分:0)

Rory's的答案和评论指向了正确的方向,但这是一个实际示例:

operators = ["+","-","/","*","**","^"]
msg = f"Example query: 8 * 4\nAllowed operators: {', '.join(operators)}\nType your query and press enter:\n"

x = input(msg)
cmd_parts = [y.strip() for y in x.split()] # handles multiple spaces between commands

while len(cmd_parts) != 3: # check if lenght of cmd_parts is 3
    x = input(msg)
    cmd_parts = [y.strip() for y in x.split()]

# verification of command parts
while not cmd_parts[0].isdigit() or not cmd_parts[2].isdigit() or cmd_parts[1] not in operators :
    x = input(msg)
    cmd_parts = [y.strip() for y in x.split()]

num1 = cmd_parts[0]
oper = cmd_parts[1]
num2 = cmd_parts[2]

res = eval(f"{num1} {oper} {num2}")
print(num1,oper,num2,"=", res)

Python Example(启用交互模式