Jump to content

Python error

SamAnw

Hello everyone!

I've been working on this program:

txt = "Prob03.in.txt"
msg = open(txt, "r")
msg = msg.read()
n=int
countCase=1
for prob in msg:
    prob =prob.split()
    i =0
    while i<2:
        prob[i] = int(prob[i])
        i=+1
    if prob[0] != prob[1]:
        print("false")
    elif prob[0] == prob[1]:
        print("true")

    

My txt file looks like this:

2
true false
true true

 

I don't understand why it's not working :/

Thankyou!

Link to comment
Share on other sites

Link to post
Share on other sites

There are a few thinks wrong, firstly you are over writing variable values  which is just bad practise

It appears that you want each line of the file in a list

txt = "Prob03.in.txt"
#strip() removed breaking space like /n or /r/n
msgs = [line.strip() for line in open(txt, 'r')]

 

next if you know how many times to loop you should use a for loop

for i in range(2):
	#code

 

which bring me on to the first real issue the first line in the text file "2" has a length of 1 so prop[1] will throw an index error.

 

You can also remove the looping all together and converting to int() as the values will be strings from the file.

 

txt = "Prob03.in.txt"
msgs = [line.strip() for line in open(txt, 'r')]

for msg in msgs:
    prob=msg.split()
    # if we don't have enough indexs then skip
    if(len(prob) != 2):
      continue
    if prob[0] == prob[1]:
      print("True")
    else:
      print("False")

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×