-4

Here is my current code:

x = int(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679)

q = int(input("How many digits of Pi would you like to Print?"))

print(x[1:y])

Sorry if that Code indenting thing didn't work, I didn't understand it.

You see, I know that it can't convert the string variable as a literal term into the integer, but what would I do from here?

The code is supposed to print Pi to a chosen amount of characters.

3
  • Error message clear - you can't subscript int variable Commented Aug 3, 2015 at 18:39
  • 2
    Also, why did you make pi an int. No matter what you do here, it will always print 3.0000.... Commented Aug 3, 2015 at 18:40
  • 1
    where do that y come from in place of q?! Either use y or q. Commented Aug 3, 2015 at 19:03

2 Answers 2

1

You can utilize string formatting for this task. To have a variable number of decimals, you simply need to parameterize that value

from decimal import Decimal
x = decimal(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679)

q = int(input("How many digits of Pi would you like to Print?"))

print("{0:.{width}f}".format(x, width=q))

Notice that the width variable in the print statement is your user input. Also notice I changed your definition of pi from an int to a decimal (because a float loses precision).

Examples:

How many digits of Pi would you like to Print?5
3.14159

How many digits of Pi would you like to Print?10
3.1415926536

How many digits of Pi would you like to Print?25
3.1415926535897931159979635
Sign up to request clarification or add additional context in comments.

Comments

1

Try following code.

 x = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"

y = int(input("How many digits of Pi would you like to Print?"))

print(x[1:y+1])

You can't use integers as list. But because the power of python you can render strings. Also care your variable names. Finally because python starts to count from 0 to n, nth number must be n+1 th position.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.