mardi 13 juillet 2021

Python - How to find variable type with if statement and type function [duplicate]

I am trying to make a command system and need to check if a variable is an int or not. I thought that if you use the type function in an if statement and then compare it to "<class 'int'>" that it would work. No error message appears but if I enter an int it says its not an int. Here is my code:

def prompt():
  usrinput = input(">>")
  return usrinput.split(' ')

r = "r/"
ad1 = "ad1"

command = prompt()
if r in command:
  if len(command) == 2:
    parameter_1 = command[1]
    print(parameter_1)
    prompt()
  else:
    print('Required parameter not given')
    prompt()
elif ad1 in command:
  if len(command) == 3:
    parameter_1=int(command[1])
    parameter_2=int(command[2])
    if type(parameter_1) == "<class 'int'>" and type(parameter_2) == "<class 'int'>":
      print(parameter_1+parameter_2)
      prompt()
    else:
      print('Parameter type not int')
      prompt()
  else:
    print('Required parameters not given')
    prompt()
else:
  print('Not a command')
  prompt()

And here is the link to my code: https://replit.com/@skelesquidstd/command-line#main.py

Aucun commentaire:

Enregistrer un commentaire