skip to Main Content

Im trying to learn python but somehow the command to generate random numbers is not working.

My code is:

import random

##First try

random_integer =  random.randint ( a: 1, b: 100 )

This is what i get.

  random_integer =  random.randint ( a: 1, b: 100 )
                                        ^
SyntaxError: invalid syntax

I am using Visual Studios and i installed some plugs already.
In the problems tag i get "a" is not defined.

3

Answers


  1. That isn’t valid python syntax. It seems like you’ve mixed up type hinting and calling a function with keyword arguments. The function you want is defined as

    random.randint(a, b)
    

    It can be called using unnamed positional parameters as in

    random_integer =  random.randint (1, 100)
    

    where the first parameter is a and the second is b.
    Or named keyword parameters where the order doesn’t matter

    random_integer =  random.randint (a=1, b=100)
    random_integer =  random.randint (b=100, a=1)
    
    Login or Signup to reply.
  2. In python if the syntax of a method or function is function_name(a,b), if you are not changing the order(sequence) of the arguments, you can directly call with the arguments without mentioning parameters’ name.

    random_integer =  random.randint ( 1, 100 )
    

    If you are not sure about the order or sequence of the parameters, then the parameter name and argument should be separated by an = sign.

    # I 've mentioned a and b as I don't know which comes first between a and b
    # note: I've changed the order a and b still you get proper result
    
    
    random_integer =  random.randint ( b= 100, a= 1 ) 
    
    Login or Signup to reply.
  3. Fixes:

    a = 1
    b = 100
    random_integer = random.randint(a, b)
    
    random_integer = random.randint(a=1, b=100)
    

    Your code didn’t work as it didn’t use proper syntax.

    random.randint(a, b)
    

    will generate a random number between a and b inclusive.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search