1

I am using python for producing random in integer between the two value from the user, My code is as follows. I am getting error:

from random import *

i1 = input('Enter the N1 :')
i2 = input('Enter the N2 :')

r = randint({0},{1}.format(i1,i2))

print r

Here I am taking i1 and i2 from user and want to produce random integer between i1 and i2.

I am getting the error:

File "index.py", line 6
    r = randint({0},{1}.format(i1,i2))
                  ^
SyntaxError: invalid syntax

4 Answers 4

4

To fix everything just do:

r = random.randint(i1, i2)

After fixing the SyntaxError you will get another error due to passing a string to randint. Just do what I did above to fix that, you don't need .format at all.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to add quotation marks/apostrophes to make {0},{1} a string:

r = randint('{0},{1}'.format(i1,i2))

This will pass a string to the random integer function though. The function expects two integers. So all you need to do is:

r = randint(i1, i2)

3 Comments

thanks , but I am getting another error after editing this. Error is : Traceback (most recent call last): File "index.py", line 6, in <module> r = randint('{0},{1}'.format(i1,i2)) TypeError: randint() takes exactly 3 arguments (2 given)
@chakladar You probably don't want the format function here. Just do r = randint(i1, i2)
@AlexThornton Please don't advertise your answer on mine
1

According to the manual, input is equivalent to eval(raw_input(prompt)), so you don't need to parse strings to integers - i1 and i2 are already integers. Instead do:

from random import randint

i1 = input('Enter N1:')
i2 = input('Enter N2:')
r = randint(i1, i2)
print r

BTW, you are missing quotes for the format string {0},{1}

Comments

1

Here's what you're trying to do:

  1. Import the randint function
  2. Get the lower and upper bounds from the user
  3. Print out a random integer between (inclusive) the bounds

Here's the code to do that:

from random import randint

a = input('Enter the lower bound: ')
b = input('Enter the upper bound: ')

print(randint(a, b))

NOTE: If you're using Python 3 you will need to convert a and b to integers e.g.

a = int(input('Enter the lower bound: '))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.