0

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

1

3 Answers 3

1

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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")

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.