0

i have string variables and for example two of them are empty "".

Those empty strings should be set to 0.

And after that, all string variables should be converted into an integer, to be able to do some checks on it and return them.

But my current problem is that my loop does not set the empty strings to 0.

I get the following output when i run the script:

['1000', '', '', '5']
Only Numbers!

And do you have an idea how i can work with the variables after the loops? Without the need of list index?

def func():
    bandwidth = 2000
    voice = "1000"
    signal = ""
    stream = ""
    business = "5"

    empty_check = [voice, signal, stream, business]
    for n in empty_check:
        if n == "":
            n = 0
    print(empty_check) # check if "" was set to 0
    try:
        for n in empty_check:
            n = int(n)
    except ValueError:
        print("Only Numbers!")
    else:
        if (empty_check[0] > 2000000) or (empty_check[0] > bandwidth):
            print("Error")
        elif (empty_check[1] > 1000000):
            print("Error")
        elif (empty_check[2] + empty_check[3]) > 95:
            print("Error")
        else:
            return bandwidth, empty_check[0], empty_check[1], empty_check[2], empty_check[3]
    
test = func()

1 Answer 1

1

Your for loops only assigned 0 to the local variable n and didn't modify the list. Instead, you should do empty_check[n] to change the value at the index inside the list.

I tried using range in your for loops so that n is used as an index in the empty_check list and successfully got an output of:

['1000', 0, 0, '5']

https://www.w3schools.com/python/python_for_loops.asp

Here is the code I used:

for n in range(len(empty_check)):
    if empty_check[n] == "":
        empty_check[n] = 0
print(empty_check)  # check if "" was set to 0
try:
    for n in range(len(empty_check)):
        empty_check[n] = int(n)
Sign up to request clarification or add additional context in comments.

1 Comment

it works for the 0 thanks, and for the integer i had to do: try: for n in range(len(empty_check)): empty_check[n] = int(empty_check[n])

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.