數字意味著數字而不是地方
我試過了,但我知道邏輯是錯誤的
N=input()
L=len(N)
N=int(N)
sum_e=0
sum_o=0
for i in range(0,L 1):
if i%2==0:
sum_e=sum_e i
else:
sum_o=sum_o i
print(sum_e, sum_o)
uj5u.com熱心網友回復:
您可以通過調制輸入值來更簡潔地實作這一點,如下所示:
N = abs(int(input('Enter a number: ')))
eo = [0, 0]
while N != 0:
v = N % 10
eo[v & 1] = v
N //= 10
print(*eo)
樣本:
Enter a number: 1234567
12 16
uj5u.com熱心網友回復:
N=input()
sum_e=0
sum_o=0
for i in N:
if int(i)%2==0:
sum_e = int(i)
else:
sum_o = int(i)
print(sum_e, sum_o)
讓它保持字串,這樣我們就可以迭代數字,然后將其轉換為整數
uj5u.com熱心網友回復:
使用字典:
N = input()
# N = '1234567'
out = {}
for c in N:
c = int(c)
key = 'odd' if c%2 else 'even'
out[key] = out.get(key, 0) c
print(out['even'], out['odd'])
# 12 16
或者使用類似于@Cobra 的方法:
N = int(input())
# N = 1234567
out = [0, 0]
while N>0:
N, n = divmod(N, 10)
out[n%2] = n
print(*out)
# 12 16
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/533040.html
標籤:Python循环if 语句