簡體   English   中英

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

[英]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轉換為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)

您必須將輸入類型轉換為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM