-2

I want to generate random numbers with a few chosen numbers. for example, if the chosen number has 2 place value, then it should print two chosen number + four value but the code throwing error message after running :(

def y(x):
    two_value = random.randint(700000,999999)
    three_value = random.randint(70000, 99999)
    four_value = random.randint(7000, 9999)
    place_value = len(x)
    if place_value == 2:
        print(f'Your random 2 digit favorite number :{x},{two_value}')
    elif place_value == 3:
        print(f'Your random 3 digit favorite number :{x},{three_value}')
    elif place_value == 4:
        print(f'Your random 4 digit favorite number :{x},{four_value}')
    else:
        print("error")
print(y(15))

"C:\Users\WIN Ultimate\PycharmProjects\new\venv\Scripts\python.exe" "C:/Users/WIN Ultimate/PycharmProjects/new/Numbergenerator.py"
Traceback (most recent call last):
  File "C:/Users/WIN Ultimate/PycharmProjects/new/Numbergenerator.py", line 35, in <module>
    print(y(15))
  File "C:/Users/WIN Ultimate/PycharmProjects/new/Numbergenerator.py", line 26, in y
    place_value = len(y)
TypeError: object of type 'function' has no len()
Chris
  • 29,127
  • 3
  • 28
  • 51
  • Your code and error messages clearly conflict (`place_value = len(y)` in error vs `place_value = len(x)` in code). Perhaps try in a new session? – Chris Sep 29 '19 at 02:32
  • The error message you've posted comes from completely different code from the code you posted. Voting to close. – user2357112 Sep 29 '19 at 02:39

2 Answers2

1

I don't get exactly what the objective of this code is, but I know the source of your error. You cannot use the len() function directly on an integer in python, you must first convert it to a string, as done below:

import random

def y(x):
    two_value = random.randint(700000,999999)
    three_value = random.randint(70000, 99999)
    four_value = random.randint(7000, 9999)
    place_value = len(str(x))
    if place_value == 2:
        print(f'Your random 2 digit favorite number :{x}{two_value}')
    elif place_value == 3:
        print(f'Your random 3 digit favorite number :{x}{three_value},')
    elif place_value == 4:
        print(f'Your random 4 digit favorite number :{x}{four_value}')
    else:
        print("error")
y(15)

instead of place_value = len(x), it is now place_value = len(str(x))

0

This code throws the error object of type 'int' has no len(), not object of type 'function' has no len(). I don't think you copied the right traceback.

When you do len(x), you are asking for the length of 15, and the error means exactly what it says: 15, an integer, does not have a length in Python.

If you are trying to get the number of digits in x, see this answer.

pauliner
  • 327
  • 1
  • 6