Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用for循环将输入一分为二_Python 3.x - Fatal编程技术网

Python 3.x 使用for循环将输入一分为二

Python 3.x 使用for循环将输入一分为二,python-3.x,Python 3.x,这就是我陷入困境的地方,我试图通过网络课程学习Python 编写一个程序,采用«number1»+«number2»形式的单个输入行,其中这两行都表示正整数,并输出两个数字的总和。例如,在输入5+12时,输出应为17 我们不应该使用split()或任何导入 我认为解决方案是使用字符和它的值43,这样子字符串,但我不确定。我唯一能确定的是,解决方案很简单,不需要任何奇特的函数或导入 以下是我认为可能接近解决的方法 S = input() for position in range(0,len(S)

这就是我陷入困境的地方,我试图通过网络课程学习Python

编写一个程序,采用«number1»+«number2»形式的单个输入行,其中这两行都表示正整数,并输出两个数字的总和。例如,在输入5+12时,输出应为17

我们不应该使用split()或任何导入

我认为解决方案是使用字符和它的值43,这样子字符串,但我不确定。我唯一能确定的是,解决方案很简单,不需要任何奇特的函数或导入

以下是我认为可能接近解决的方法

S = input()
for position in range(0,len(S):
      #code for substrings 5 to number1, and 12 to number2
result = int(number1)+int(number2)
print(result)
使用:

如果您不能使用
str.partition
并想对
循环使用
,那么
枚举
应该有帮助:

for i, c in enumerate(line):
    if c == '+':
        # what goes here?

回答

S = input()
for position in range(0, len(S)):
plus=S[position]
    if (plus!="+"):
      continue
    number1=int(S[0:position])
    number2=int(S[position+1:len(S)])
    print(number1+number2)

你不能只使用两个原始的输入()表达式吗?不,到目前为止,我们阅读的材料没有涉及到它们。相关:。。从技术上讲,这是正确的,但是如果OP不应该使用
split()
,那么我认为使用
partition()
就不太合适了。但是,如果没有看到问题中描述规则的未引用部分,很难说,而且问题标题似乎提到了for循环。是的,如果可以避免的话,我们必须使用for循环和no partition()。在这门课程中,我们没有深入挖掘函数或导入。这门课程非常基础,所有的解决方案都应该尽可能简单。我非常感谢您的帮助,但我认为我也不能使用enum()。正如问题所说,在for循环的帮助下,将形式(5+12)中给出的输入字符串拆分为两个子字符串number1=5,number2=12。这是我一个人做不到的。我可以将其转换为整数,然后自己添加。@Aenohe代替
enumerate
尝试
range(len(line))
S = input()
for position in range(0, len(S)):
plus=S[position]
    if (plus!="+"):
      continue
    number1=int(S[0:position])
    number2=int(S[position+1:len(S)])
    print(number1+number2)