-1

I am making an AI, I want the code to understand that something is an integer

elif inp==("i am", int):
  print("You are "x" years old")

inp is my variable

elif="i am", int ,"years old":
  print("You are", int ,"years old")

This is what I want. But for it to actually work, I want it to understand that there is an integer there.

If they said "I am awesome" it would do it, but if they put "I am 14" it would print You are "x" years old. I am ok with the printing bit and with how old they actually are. But, I just want the code to recognize that there is a number there.

akshat
  • 1,219
  • 1
  • 8
  • 24

3 Answers3

1

Given simple text, it is fairly easy to extract an integer (python 3 code):

import re

while True:

    # I have no idea where your text is coming from, this is for testing
    line = input("enter text: ")
    if not line: break

    # The regular depression means "one or more characters in the range 0-9"
    m = re.search(r'([0-9]+)', line)
    if m:
        print(m.groups()[0])   # << This hold the integer string

    # if m is false, there is no integer

If there could be more than one integer then a different solution might be required.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

If your input string is always going to be in same format, i.e. last word would be integer or something else. You could try:

my_input_list = my_input.split()  # Split your sentence into list
last_word = my_input_list[-1]     # Get last word
if isinstance(last_word , int):   # Check is last word in "int" type
    print("You are {age}" years old) 
else: 
    print(my_input)

But as you are writing AI, your code will get more complicated in future. You should explore using regex as @Rakesh mentioned.

akshat
  • 1,219
  • 1
  • 8
  • 24
0

Add a type validation before printing you can also add raise TypeError or InputError if you want to.

if type(age) == type(1):
    #continue with printing
else:
    raise InputError('age must be an integer)

Or better still print('age must be an integer ') instead of raising error

akshat
  • 1,219
  • 1
  • 8
  • 24
Bello Mayowa
  • 45
  • 2
  • 7
  • it is not advisable to use `type()` for this. Python has `isinstance()` function for this very purpose. Read this for more info https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance – akshat May 17 '18 at 09:52