0

Ok so I'm trying to make a program that takes a number and then goes through random numbers until it finds the one given. This is my code so far:

 import random
number=input("Enter any number: ") #takes input from user
length=len(number) #gets the length of the number
zero=("0"xlength) #is supposed to set the number of zero's to the number length. eg if the length is "4" it returns "0000"

I don't know how to get a number to replicate itself a variable amount of times.

  • 6
    What does this have to do with `random`? there's nothing random here. Anyway, your code will work if you convert `length` to `int` and use the proper operator: `zero = '0' * int(length)` – DeepSpace Dec 16 '17 at 18:13
  • 1
    Possible duplicate of [In Python, how do I create a string of n characters in one line of code?](https://stackoverflow.com/questions/1424005/in-python-how-do-i-create-a-string-of-n-characters-in-one-line-of-code) – quamrana Dec 16 '17 at 18:35

1 Answers1

0

You can't call len() on an integer.
len() returns the actual length of the passed argument, so len(33) would return 2, because in the number 33 there are 2 characters, but that is not something you can do in Python.

Instead, you can simply do:

number = input("Enter any number: ") # takes input from user
number = int(number) # convert number to an integer
zero = '0' * number # multiplies '0' by number

The reason you have to convert number to an integer is because input() returns a string, and you can't multiply a string by a string. Example:

>>> number = '4'
>>> zero = '0' * number
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    zero = '0' * number
TypeError: can't multiply sequence by non-int of type 'str'

Instead, this would be right:

>>> number = 4
>>> zero = '0' * number
>>> print(zero)
0000
teolicht
  • 245
  • 2
  • 6
  • 13