我正在做一个简单的计算器,可以计算多个数字。我有一个更简单的计算器所需要的代码。你知道吗
此代码段试图分解字符串。我在oper_lib
变量中放置运算符时遇到问题
另外,我可以用一个泛型变量定义一个函数,并在需要使用它的任何东西上调用同一个函数吗?你知道吗
>""" basic calc - designed to take multiple >variables """
from datetime import *
now = datetime.now()
#Intro
print ("\n")
print ("Welcome to BasicCalc:Unstable! \n" )
print ("If you need HELP, type help \n")
print (now)
#Beginning processing intake
ui1 = input("Please enter figure: ")
intake_list = ui1.split(" ")
lenth_list= len(intake_list)
if lenth_list % 2 == 0:
print ("invalid entry")
else:
print ("")
"""
Thoughts on this/ ideas:
- build a secondary math op list
- add two for - in loops in quick succession
"""
def do_math(intake_list):
""" proforms math function from a list"""
oper_lib = [
"+" ,
"-" ,
"*" ,
"/"
]
for i in intake_list:
for n in i:
if n in oper_lib:
intake_list.insert(i-1 , " ")
intake_list.insert(i+1 , " ")
print(intake_list)
print (do_math(intake_list))
print (intake_list)
print (lenth_list)
在数学中,您要遍历用户输入的字符列表。如果用户输入了“5-5”,则列表包含['5'、'-'、'5']。因此,当您对它进行迭代时,在使用迭代器变量i时会出现一个错误,它的值是“-”。您的程序正在尝试从行中的“-”中减去1:
我建议这样做:)
至少在一开始,认为for循环遍历“set”/“array”/“list”/等中的每一项可能会有所帮助。恰当的说法是for循环在提供的iterable中的每个值上迭代。你知道吗
上面的内容将打印到控制台。。。与return关键字不同)
然而
上面会打印出来
我想我知道你想用第二个循环做什么,但是你做了太多的工作,这会给你不正确的结果。(给你自己和你未来几年/几十年的调试提示:在头脑中或纸上用简单的输入运行代码,比如一个包含0、1或2个值的列表,充当程序,逐行运行,看看它会做什么。)在字符串上迭代的次数最多是一次。基于以上,无论是
i
还是n
都没有提供任何关于列表中的索引/键/“位置”的信息,这似乎是您要插入列表中所要寻找的。你知道吗您要做的是抓住当前的“位置”,并在iterable上用空格围绕它。你知道吗
一个简单的解决方案是保留一个计数器(每个数字或运算符加1)。这将允许您跟踪需要为当前值放置空间的位置。你知道吗
另一种解决方案可能是计算新列表中的项目数,并根据该数字进行追加。你知道吗
相关问题 更多 >
编程相关推荐