【问题标题】:How do I use input in def (Python)如何在 def (Python) 中使用输入
【发布时间】:2020-04-29 08:41:17
【问题描述】:
在编码方面我是新手。如果您能帮助我解决有关编码的问题,我将不胜感激。我尝试在我的 def 中使用输入但不起作用。
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
result = estimate_pi(n)
print (result)
【问题讨论】:
标签:
python
function
random
input
pi
【解决方案1】:
python 的输入函数是一个字符串,而您的代码需要一个整数。只需将 n 转换为整数就可以了。
n = int(input("Enter A Random Number"))
【解决方案2】:
您必须将输入从string 转换为int:estimate_pi(int(n))
正确的代码是:
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
result = estimate_pi(int(n))
print (result)
【解决方案3】:
您必须将输入类型转换为整数:
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
n = int(n) #converting n from string to integer
result = estimate_pi(n)
print (result)
【解决方案4】:
我猜,你问的是在“def”块中使用“input()”方法。
我尝试如下,它工作。
让我知道您遇到的具体错误是什么
def estimate_pi():
n =int input("Enter A Random Number")
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle/num_point_total
result = estimate_pi()
print (result)