Ask coding questions

← Back to all posts
User enters number output as string
Divad31188 (0)

Hey guys, i know i've read it somewhere but how can I switch from a number to a Text in Python?
e.G. What did you wanne Eat tip 1 for Burger King and 2 for McDonalds, or something like that🤔😅

Comments
hotnewtop
InvisibleOne (3197)

Just convert the input to an integer with int()

print("How many burgers do you want to eat? ")
answer = int(input())

if answer >= 10:
  print("That's too many!")
elif answer == 1:
  print("Are you sure you don't want two?")

Just keep in mind that if they submit something other than a number, you will get an error, so maybe you want to try something like this:

# custom input function
def int_input(prompt):
  while True:
    try:
      result = int(input(prompt))
      if result:
        return result
        break
      else:
        print("You didn't give me an answer!")
    except:
      print("Please input an integer!")

And then when you want to get an integer input:

answer = int_input("Give me a number: ")
Coder100 (18872)

You can convert a string to int: int('1')

You can convert a int to string: str(1)

but in your case, none of those are necessary, just use if statements!

var = input('what you want ')
if var == '1':
  # ...
elif var == '2':
  # ...
else:
  print('what')
xfinnbar (147)

If the number is decimal, use float(). If it is not decimal, use int().