'can I use string and integer in while loop in python?

Hello I am new in Python and maybe it is stupid question but can you help me with this code?

while True:
k = int(input("type: "))
l = k % 2
if l==0:
     print("luwi")
elif l != 0:
     print("kenti")

i want to add elif where is said that if k == "exit" code breaks how make system to read not only integers but strings as well?or it is impossible? P.s I am very new in python :D



Solution 1:[1]

You would get an error with int(input("type: ")) when entering a non-numeric string.

Try:

while True:
    s = input("type: ")  # User inputs string
    try:
        k = int(s)       # tries converting string to int (exception if unsuccessful)
        l = k % 2
        if l==0:
            print("luwi")
        elif l != 0: 
            print("kenti")
    except:               # exception tells you entry was not an integer
        if s == "exit":   
            break         # entered exit
        else:
            print('Enter a number or "exit"')  # ask user to enter number or exit

Solution 2:[2]

I think you should be very careful with the datatype problem. You have to make sure that when k compare with an other variable they have the same datatype. Here are few functions that could change the data type. str(), int()

Solution 3:[3]

How about checking for exit first, and then continuing to convert to int after that?

while True:
    k = input("type: ")
    if k == 'exit':
        break
    else:
        k = int(k)
    l = k % 2
    if l == 0:
        print("luwi")
    elif l != 0:
        print("kenti")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tkun
Solution 3 Adam Hopkins