Python 3.x 如何让Python计算出用户给定半径的圆的面积
我可以先说我对Python和编码这整件事还是新手吗 这是我的代码:Python 3.x 如何让Python计算出用户给定半径的圆的面积,python-3.x,geometry,area,Python 3.x,Geometry,Area,我可以先说我对Python和编码这整件事还是新手吗 这是我的代码: pi = 3.14159265 choice = input ("Enter a number between 1-5:") choice = int (choice) if choice == 1: radius = (input ("Enter x:") area = ( radius ** 2 ) * pi print ("The Area of the circle is, " =area)
pi = 3.14159265
choice = input ("Enter a number between 1-5:")
choice = int (choice)
if choice == 1:
radius = (input ("Enter x:")
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " =area)
if choice == 2:
radius = (input ("Enter x:")
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " =area)
if choice == 3:
radius = (input ("Enter x:")
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " =area)
我在area=radius**2*pi的每一个位置都不断得到一个语法错误
我想知道为什么会发生这种情况,解决办法是什么,因为我对这种情况很陌生,可能很快就会发生,我真的很愚蠢
无论如何,谢谢你,你的代码的问题是你把半径读成一个字符串,然后你试图对一个整数字符串进行数学运算 通常,当您从用户处读取输入时,最好将变量转换为您希望使用的数据类型 这将解决您的问题:
import math
pi = math.pi
choice = input ("Enter a number between 1-5:")
choice = int (choice)
if choice == 1:
radius = float(input ("Enter x:"))
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " + str(area))
if choice == 2:
radius = float(input ("Enter x:"))
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " + str(area))
if choice == 3:
radius = float(input ("Enter x:"))
area = ( radius ** 2 ) * pi
print ("The Area of the circle is, " + str(area))
正如您所看到的,我对您的print语句做了一些更改,因为应该使用+运算符而不是=运算符,并且您还应该使用str将数值转换为字符串
我还建议您使用π常量,而不是硬编码π值
最后,我无法理解为什么您使用3个计算完全相同的案例,其中3行代码的结果可能相同。radius=input Enter x:的行不正确,您可能需要radius=FLOAT input Enter x:。哦,=区域也是无效的。删除=。当你只测试3个选项时,为什么是1-5?