gpt4 book ai didi

python - 只是 Python 中的一个输入

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:13 24 4
gpt4 key购买 nike

我刚刚开始学习 Python。由于这是我的第一语言,如果这太容易了,请不要对我苛刻。我不知道如何解决这个问题。这是我编写的程序:

a=input("Enter pyramid base size ")
H=input ("Enter pyramid height size ")
P=a*a+2*a*h
print (P)

但是结果是这样的:

Enter pyramid base size 2
Enter pyramid height size 2
Traceback (most recent call last):
File "D:\Program Files (x86)\Python\pyramid.py", line 3, in <module>
P=a*a+2*a*h
TypeError: can't multiply sequence by non-int of type 'str'

最佳答案

收到的输入类型是字符串,但对于您的等式,需要数字。您可以将输入转换为整数或 float ,然后进行数学运算

a = int(a)
h = float(h)

现在您可能需要检查输入是否可以转换为数字,您可以执行以下操作:

try:
h = int(h)
except ValueError:
print 'the input couldnt be converted into an integer'

编辑

那么,你的代码应该是这样的

a = input("Enter pyramid base size ")
h = input ("Enter pyramid height size ")

try:
a = int(a)
h = int(a)
p = a*a + 2*a*h

print (p)
except: ValueError:
print 'Input cannot be converted to an integer'

关于python - 只是 Python 中的一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16449897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com