[英]How do I use input in def (Python)
在编码方面,我是新手。 如果您能帮助我解决有关编码的问题,我将不胜感激。 我尝试在我的 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 是一个字符串,而您的代码需要一个 integer。 只需将 n 转换为 integer 就可以了。
n = int(input("Enter A Random Number"))
您必须将输入从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)
您必须将输入类型转换为 integer:
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)
我想,您是在询问在“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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.