[英]Why is my variable not being accessed? and why do my outputs come together instead of returning in a new line
我正在尝试编写一个程序,该程序返回切片在一起的偶数和奇数字符串。 在编译时这样做,我在“else:”语句中定义的“odd”变量不可访问。 可能是什么问题呢? '''
num = int(input())
even_L = []
odd_L = []
for stdin in range(num):
s = input()
inputs = [n for n in s]
for names in inputs:
for name in range(len(names)):
if name % 2 == 0:
even_L.append(s[name])
even = "".join(even_L)
else:
odd_L.append(s[name])
odd = "".join(odd_L)
new = even + 2 * " " + odd
#I have tried moving the indentation also
print (new)
'''显示的错误是:'''
Traceback (most recent call last):
File "Solution.py", line 18, in <module>
new = even + 2 * " " + odd
NameError: name 'odd' is not defined
'''
和
我试图以各种方式做到这一点。 但即使我成功地安排了字符串。 因为我必须输入 2 个名字,输出也应该返回两个名字。 但这里它返回两个名字,但名字必须分开对吗? '''
let's say two names i.e. Hacker, Rank
the required output is: Hce akr and Rn nk
but mine output is Hce akr and HceRn akrnk
why does the second output comes paired with first output?
'''
我的问题代码是:
num = int(input())
even_strings = []
odd_strings = []
rev_nam = []
final_name = []
for i in range(num):
S = input()
rev_nam.append(S)
for name in rev_nam:
for i in range(len(name)):
if i%2 == 0:
even_strings.append(name[i])
else:
odd_strings.append(name[i])
even_formatted_string = "".join(even_strings)
odd_formatted_string = "".join(odd_strings)
names = even_formatted_string + 2 * " " + odd_formatted_string
print(names)
输出 :
Hce akr
HceRn akrak
所需输出:
Hce akr
Rn ak
我尝试在导入 os 模块并使用后清除输入
os.system('cls')
但它似乎不起作用,或者我不知道把它放在哪里。 任何参考
您的“奇数”变量声明位于 else 块内,并且只能在运行时访问,如果您不进入 else 块,您的变量将不存在。 在 else 块之外给它一些默认值。
我找到了我的问题的答案。 添加这两个变量的原因是将字符串声明为全局变量。 所以要重新迭代字符串,我必须在本地范围内声明变量。
num = int(input())
for stdin in range(num):
s = input()
new = ''
odd = ''
even = ''
for name in range(len(s)):
if name % 2 == 0:
even += s[name]
else:
odd += s[name]
new = (even +" " + odd)
print(new)
执行此操作后,一旦我输入输入,就会提示输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.