Kero Fawzy
Kero Fawzy

Reputation: 700

my program dose not run because of confuse between integer value and string

my program confuse between integer value and string 
import random


def test():
    num=random.randrange(100,1000,45)
    while True:
        ans=run(num)
        print ans
        ss=raw_input("if you want to exit press t: ")
        if ss=='t':
            break

def run(userinput2):
    first = int(userinput2/20)
    print "i will send it in %s big pack"%str(first)
    userinput2=userinput2%20
    second =int(userinput2/10)
    print "i will send it in %s med pack"%str(second)
    third =userinput2%10
    print "i will send it in %s med pack"%str(third)



def main():
    print "the began of pro"
    print "@"*20
    userinput=raw_input("test or run: ")
    if userinput.lower()=='test':
        test()
    else:
        while True:
            userinput2=int(raw_input("press t to exit or chose a number:"))
            if userinput2 =='t':
                break
            else:
                answer=run(userinput2)


if __name__ == "__main__":
      main()

this piece of code i has error in it

userinput2=int(raw_input("press t to exit or chose a number:")) if userinput2 =='t':

if i change it to string i had it not accept string and if make it string it not accept integers

Upvotes: 1

Views: 40

Answers (1)

John1024
John1024

Reputation: 113944

I think that this covers the cases you need:

while True:
    userinput2=raw_input("press t to exit or chose a number:")
    if userinput2 =='t':
        break
    try:
        userinput2 = int(userinput2)
    except ValueError:
        print('That was neither a number nor a "t".  Try again.')
        continue
    answer=run(userinput2)

Upvotes: 2

Related Questions