-3

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.

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)
Code Pope
  • 5,075
  • 8
  • 26
  • 68

4 Answers4

0

Input function of python is a string whereas your code is expecting an integer. Simply cast n as integer and it should be fine.

n = int(input("Enter A Random Number"))
Jason Chia
  • 1,144
  • 1
  • 5
  • 18
0

You have to convert the input from string to int: estimate_pi(int(n)) The correct code would be:

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)
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

You've to convert your input type to 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)
Vishal Upadhyay
  • 781
  • 1
  • 5
  • 19
0

I guess, you are asking about using the "input()" method inside the "def" block.

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)
aravindp03
  • 21
  • 1