简体   繁体   English

如何在 def (Python) 中使用输入

[英]How do I use input in def (Python)

I'm a newbie when it comes to coding.在编码方面,我是新手。 I would highly appreciate it if you can help me solving my problem regards to coding.如果您能帮助我解决有关编码的问题,我将不胜感激。 I tried to use input in my def but doesn't work.我尝试在我的 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)

Input function of python is a string whereas your code is expecting an integer.输入 python 的 function 是一个字符串,而您的代码需要一个 integer。 Simply cast n as integer and it should be fine.只需将 n 转换为 integer 就可以了。

n = int(input("Enter A Random Number"))

You have to convert the input from string to int : estimate_pi(int(n)) The correct code would be:您必须将输入从string转换为intestimate_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)

You've to convert your input type to integer:您必须将输入类型转换为 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)

I guess, you are asking about using the "input()" method inside the "def" block.我想,您是在询问在“def”块中使用“input()”方法的问题。

I tried as below and it worked.我尝试如下,它奏效了。

Let me know what exactly is the error that you are getting让我知道你得到的错误到底是什么


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM