1

I'm coding in python and I want to find out whether there's a way to change the data type of an input. I've devised a code to represent my question:

        menu= input("test>>> ")
    if (menu)==("forprint"):
    fortimes= input ("range>>>>")
    forprintwhat= input ("print>>>>>")
    for x in range (fortimes):
        print (forprintwhat)

Now obviously, I get this error:

Traceback (most recent call last):
File "C:/Users/vas71/AppData/Local/Programs/Python/Python38/leaf.py", line 15, in <module>
for x in range (fortimes):
TypeError: 'str' object cannot be interpreted as an integer

Note: the error message says 'line 15' because I'm copying it from a larger body of text. My question is, how do I make the string an integer so that my code works? Is it possible? Thank you for the help!

1 Answers1

2

You can cast your input to integer:

fortimes = int(input("range>>>>"))

Please allow me to suggest you to have input validation by using try-except block. Something simple like:

while True:
    try:
        fortimes = int(input("range>>>>"))
        break
    except:
        print("Enter valid range (numeric)")

In case a user enters invalid range input.

Sercan
  • 2,081
  • 2
  • 10
  • 23