user12828597
user12828597

Reputation:

Defining the type of variable! PYTHON

I am doing a small console program. You input the data and then program puts it in .txt file. The data is: Country Year of birth Month of birth Day of birth Real name Nickname

I decided to do a definition for every variable, so if user types an integer in "Country" it gives him a warning and vice versa. Here is the code:

countryU = input('Страна проживания ')
yearU = input('Год рождения ')
monthU = input('Месяц рождения (его порядковый номер) ')
dayU = input('День рождения ')
nameU = input('Имя ')
nicknameU = input('Никнейм ')
aaaaa = 5
from random import *
u = randint(1,1000000000000)
uinfoname = str(u) + '.txt'

if type(countryU) == str:
    if type(yearU) == int:
        if type(monthU) == int:
            if type(dayU) == int:
                if type(nameU) == str:
                    if type(nicknameU) == str:
                        if countryU == '':
                            print('Вы ввели не все данные! Перезапустите программу и введите все.')
                            input('Press any key to exit...')
                        else:
                            if yearU == '':
                                print('Вы ввели не все данные! Перезапустите программу и введите все.')
                                input('Press any key to exit...')
                            else:
                                if monthU == '':
                                    print('Вы ввели не все данные! Перезапустите программу и введите все.')
                                    input('Press any key to exit...')
                                else:
                                    if dayU == '':
                                        print('Вы ввели не все данные! Перезапустите программу и введите все.')
                                        input('Press any key to exit...')
                                    else:
                                        if nameU == '':
                                            print('Вы ввели не все данные! Перезапустите программу и введите все.')
                                            input('Press any key to exit...')
                                        else:
                                            if nicknameU == '':
                                                print('Вы ввели не все данные! Перезапустите программу и введите все.')
                                                input('Press any key to exit...')
                                            else:
                                                if (len(str(nicknameU)) < aaaaa):
                                                    print('Твой никнейм недостаточно длинный! (минимум 5 символов) Перезагрузите программу и введите все правильно.')
                                                    input('Press any key to exit...')
                                                else:
                                                    print('Вы -', nameU, 'из страны', countryU, '')
                                                    print('Ваша дата рождения: месяц', monthU, 'число', dayU, 'год', yearU, '')
                                                    print('Ваш никнейм на сайте -', nicknameU, '.')
                                                    print('Приятного времяпрепровождения!')
                                                    output = open(uinfoname, 'x')
                                                    print(countryU, file=output)
                                                    print(yearU, file=output)
                                                    print(monthU, file=output)
                                                    print(dayU, file=output)
                                                    print(nameU, file=output)
                                                    print(nicknameU, file=output)
                                                    output.close()
                                                    input('Press any key to exit...')
                    else:
                        print('Никнейм не должен содержать специальные символы или цифры!')
                        input('Press any key to exit...')
                else:
                    print('Имя не должно содержать специальные символы или цифры!')
                    input('Press any key to exit...')
            else:
                print('День вашего рождения является числом!')
                input('Press any key to exit...')
        else:
            print('Месяц вашего рождения является числом!')
            input('Press any key to exit...')
    else:
        print('Год вашего рождения является числом!') #pay attention to this string, this is the problem
        input('Press any key to exit...')
else:
    print('Название вашей страны не может содержать специальные символы или цифры! (Если название вашей страны все-таки их содержит, напишите название без них.')
    input('Press any key to exit...')

Don't mind, I am Russian and I use Russian language. Well, to the problem: When I run the program and type everything correctly (integer to integer, string to string), it says: Год вашего рождения является числом! (the problem string) It means "Your year of birth should be a number!" And even if I type the country incorrectly (integer), it says the same. So whatever I type, it gives me that string. I also used isinstance, but it is much worse here. Please help me!

Upvotes: 0

Views: 385

Answers (7)

LeopardL GD
LeopardL GD

Reputation: 132

You should keep in mind that input() always gives you a string. Try this:

try:
    mathproblem = int(input('23516 * 84818^81'))
except ValueError:
    print('Dude you should type a number...')

Upvotes: 0

ChufanSuki
ChufanSuki

Reputation: 93

input([prompt]) always return a string type.

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

If you want to do type checking, you can use isinstance(object, classinfo) which return True if the object argument is an instance of the classinfo argument and raise a exception when meeting invalid value.

A example:

def checkType(s):
    if not isinstance(s, str):
        # This is (a simple form of) how you raise your own custom exception:
        raise Exception('It must be a string')
    else: 
        pass

print(checkType('abc'))
print(checkType(1))
print("This line will never run!")

Upvotes: 0

t0mas
t0mas

Reputation: 147

To remove the amount of IF statements you have, you can simply ask that the input is an integer or string when you are asking for the variable in the first few lines, for example:

countryU = str(input('Страна проживания '))
yearU = int(input('Год рождения '))

This way you don't need to check if the input was an integer or string as it will just act like an integer or string. If an charaters is inputted for the year python will send back an error. to fix this you can put:

if countryU != int():
print('Год вашего рождения является числом!') # remember to indent/tab this line!!

the '!=' means is NOT equal to, so if the country is not an integer output " Год вашего рождения является числом!".

I hope this helps, this means you don;t need to check if it is a str/int because python does it for you, you only need to check if it IS NOT a srt/int.

Upvotes: 0

Allaye
Allaye

Reputation: 950

userinput = input ("Enter your Age")
try:
   value = int(userinput)
   print("Input is an integer number. Number = ", valuee)
except ValueError:
  try:
    value = float(userinput)
    print("Input is a float  number. Number = ", value)
  except ValueError:
      print("No.. input is not a number. It's a string")

Upvotes: 0

chepner
chepner

Reputation: 530950

Much of your code is catering to a case that can never happen, namely that the return value of input is not a str value. Further, if you simply exit immediately whenever you use input('Press any key to exit...'), there is no need to indent the following code. With that in mind, you code instantly reduces to something like

from random import *

countryU = input('Страна проживания ')
yearU = input('Год рождения ')
monthU = input('Месяц рождения (его порядковый номер) ')
dayU = input('День рождения ')
nameU = input('Имя ')
nicknameU = input('Никнейм ')
aaaaa = 5
u = randint(1,1000000000000)

uinfoname = str(u) + '.txt'


if countryU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if yearU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if monthU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if dayU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if nameU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if nicknameU == '':
    print('...')
    input('Press any key to exit...')
    sys.exit()

if (len(str(nicknameU)) < aaaaa):
    print('...')
    input('Press any key to exit...')
    sys.exit()

print('Вы -', nameU, 'из страны', countryU, '')
print('Ваша дата рождения: месяц', monthU, 'число', dayU, 'год', yearU, '')
print('Ваш никнейм на сайте -', nicknameU, '.')
print('Приятного времяпрепровождения!')
output = open(uinfoname, 'x')
print(countryU, file=output)
print(yearU, file=output)
print(monthU, file=output)
print(dayU, file=output)
print(nameU, file=output)
print(nicknameU, file=output)
output.close()
input('Press any key to exit...')

Upvotes: 0

Ivan
Ivan

Reputation: 1455

All your inputs are strings, you can handle integers as int(str_var)

Upvotes: 0

TVASO
TVASO

Reputation: 501

The input() method always returns a string. If you want the corresponding variable to be an integer, you should cast the string into an integer using the int() method.

So:

year = int(input("Please enter a year"))

The same goes for other types of variables, but with the float() method for floats and so on.

Upvotes: 1

Related Questions