Python try, except does not update variable

Asked 2 years ago, Updated 2 years ago, 47 views

ininin=input().rstrip().split('')
sakana, poi, Durability = int(inin[0]), int(inin[1]), int(inin[2])

d = Durability
count = 0

def check(d,w,count,poi):
    if d>w:
        count+=1
        d=d-w
    else:
        poi-=1
        if poi>0:
            d = Durability
        check(d,w,count,poi)

for_in range(sakana):
    w = int(input())

    try:
        check(d,w,count,poi)
    exceptionRecursionError:
        break

print(count)

For example, the count remains zero and does not change, why?
I don't know the solution at all.I'm self-taught, so it might be a dirty code. Sorry.
Thank you for your cooperation.

python python3

2022-09-30 21:40

1 Answers

try, except is irrelevant, because count in count=0 and print(count) and count in def check(d,w,count,poi): refer to a different count.

The count+=1 result is valid only during one def check(d,w,count,poi): call and does not affect the count outside it or the count of the next call.

To use the same count, remove the count, as a parameter from def check(d,w,count,poi): and insert the global count before if d>w: at the beginning of the process.

It will be as follows.

ininin=input().rstrip().split('')
sakana, poi, Durability = int(inin[0]), int(inin[1]), int(inin[2])

d = Durability
count = 0

def check(d,w,poi):# Remove parameter
    Use the global count# global variable

    if d>w:
        count+=1
        d=d-w
    else:
        poi-=1
        if poi>0:
            d = Durability
        check(d,w,poi)# Remove parameter

for_in range(sakana):
    w = int(input())

    try:
        check(d,w,poi)# Remove parameter
    exceptionRecursionError:
        break

print(count)

Consider taking action on other variables, if necessary.


2022-09-30 21:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.