[英]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.