我试图制作一个Python程序,它返回输入的原子序数的离子电荷,并提供一些额外的信息。我只在获取元素的离子电荷方面有问题。其他信息代码正在正常工作。
我该怎么做呢?
您可以看到下面的代码:
from mendeleev import element
while True:
aNum=int(input("Please enter the atomic number:\t"))
if aNum<0 or aNum>118:
print("\nPlease enter a valid atomic number!\n")
else:
break
e=element(aNum)
n=e.name
s=e.symbol
#The problem occurs at the line below.
c=e.charge
#The problem occurs at the line above.
print("""Information about the element that has atomic number {} is below:
\nName: {}
Symbol: {}
Ionic Charge: {}""".format(aNum,n,s,c))
错误是这样的:
AttributeError: 'Element' object has no attribute 'charge'
从现在开始,谢谢!
发布于 2022-02-02 12:38:12
所以快速看看文档给了我这个,
from collections import Counter
charges = []
for ir in e.ionic_radii:
charges.append(ir.charge)
print(charges)
print(Counter(charges).most_common(1)[0][0]) #most occuring charge
输出:
Please enter the atomic number: 8
[-2, -2, -2, -2, -2]
-2
ionic_radii函数还包含某些其他值,如自旋、原点等。
发布于 2022-02-02 12:48:42
下面是您的代码的一个更Pythonic版本,它执行您预期的任务:
from mendeleev import element
from mendeleev.ion import Ion
while True:
atomic_number = int(input("Please enter the atomic number: "))
if 0 < atomic_number < 119:
break
else:
print("Please enter a valid atomic number!")
e = element(atomic_number)
charges = [_.charge for _ in e.ionic_radii]
print(f'''
Information about the element that has atomic number {atomic_number} is below:
\tName: {e.name}
\tSymbol: {e.symbol}
\tIonic Charge: {Ion(atomic_number)} {charges}
''')
下面是一个样本输出:
Please enter the atomic number: 1
Information about the element that has atomic number 1 is below:
Name: Hydrogen
Symbol: H
Ionic Charge: H⁺ [1, 1]
Please enter the atomic number: 8
Information about the element that has atomic number 8 is below:
Name: Oxygen
Symbol: O
Ionic Charge: O⁺ [-2, -2, -2, -2, -2]
https://stackoverflow.com/questions/70955488
复制相似问题