3 variable, 3 loops into 1 loop with 3 variables?

This is the place for queries that don't fit in any of the other categories.

3 variable, 3 loops into 1 loop with 3 variables?

Postby benwhelan94 » Fri Apr 25, 2014 2:05 pm

How would I go about crunching this code into a single loop where it still tells you which specific input valuable is not valid (ie non-numerical).




Code: Select all
while True:
    try:
        a=float(input("a: "))
        break
    except ValueError:
        print("Input for a non-numerical")
        pass
       

while True:
    try:
        b=float(input("b: "))
        break
    except ValueError:
        print("Input for b non-numerical")
        pass
       

while True:
    try:
        c=float(input("c: "))
        break
    except ValueError:
        print("Input for c non-numerical")
        pass




Any help would be appreciated! x
benwhelan94
 
Posts: 19
Joined: Wed Apr 23, 2014 1:25 pm

Re: 3 variable, 3 loops into 1 loop with 3 variables?

Postby Mekire » Fri Apr 25, 2014 2:22 pm

Well, basically this means it is time to learn functions.
You also need to realize that when you want a group of variables it is actually preferred to use a container like a list or a dict.

Take a look:
Code: Select all
def get_numeric_input(name):
    while True:
        try:
            return float(input("{}: ".format(name)))
        except ValueError:
            print("Input for '{}' non-numerical.".format(name))


numerical_inputs = {var : get_numeric_input(var) for var in ["a","b","c"]}
print(
numerical_inputs)
print(
numerical_inputs["a"])

-Mek
User avatar
Mekire
 
Posts: 982
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 3 guests