I am starting to learn python as my first programming language, but i ran into a problem while trying to make a function that calculated the missing variable in the simple equation v= u+at.

The problem is that i am incapable to change a variable's value from False to True during a for loop. I tried using the vars()[] function to convert string to an usable variable, but the change in the variable doesn't seem to register.

I appreciate any solutions to this problem or any type of help on any incorrect or inefficient use of code in my function.
(The commented part doesn't seem cause problems, but i posted it regardless in case there is something i overlooked.)

``````def F1(v,u,a,t):
'''Enter 3 values using None for the missing one to calc using v=u+at'''
vTrue=False
uTrue=False
aTrue=False
tTrue=False
numVars=0
for i in ('v','u','a','t'):
if type(vars()[i])== type(1) or type(vars()[i])==type(0.1):
print('val correct')
vars()[i+'True']=True
numVars+=1
##        elif type(vars()[i])!= type(None):
##            print('Error, Wrong input type entered')
##            return 'Error'
##        print(vars()[i+'true'])
##    if numVars<3:
##        return None
##    elif numVars==4:
##        return(v,u,a,t)
##    if vtrue==False:
##        v=u+(a*t)
##        return(v,u,a,t)
##    if utrue==False:
##        u=v-(a*t)
##        return(v,u,a,t)
##    if atrue==False:
##        a=(v-u)/t
##        return(v,u,a,t)
##    if ttrue==False:
##        t=(v-u)/a
##        return(v,u,a,t)
##    else:
##        print('No answer found')
##        return('Error')``````

## All 7 Replies

Hmm that type-checking is from outer space.
You should not use `vars()` . `vars()` or `locals(),globals()` provides low level access to variables created by python.
Dont use python internal working in your code.

To check for integer or float here a couple of way.
Here you only get out of loop if input is a integer or float.

``````while True:
try:
number = float(input('Enter a number: '))
print('val correct %s' % number)
break
except ValueError:
print('Please only numbers,try again')``````

`type()` is not good to use,we can use `isinstance()` instead.

``````l = [1, 2.5, 'a']

for item in l:
if isinstance(item, (int,float)):
print('%s is a number' % item)
else:
print('%s is not number' % item)

"""Otuput-->
1 is a number
2.5 is a number
a is not number
"""``````

Type-checking in python is something that not so popular.

Need to know the type of an object? Let me make a brief argument: No, you don't.
Just use the object as if it was whatever you expect it to be, and handle any errors that result.

Here is how you can find which variables are None

``missing_list = [ i for (i, z) in enumerate((v, u, a, t)) if z is None ]``

This returns a sublist of [0, 1, 2, 3] with the indexes of the variables equal to None.

Receive the variables as a tuple and then use each item as your variable.

``````def test_num_variables(*args):
print "number of variables =", args, type(args), len(args)
os = -1
if None in args:
os=args.index(None)
print "finding None =", os, args[os]
else:
return

## assumes that the check for numbers has already been done
total = 0
for idx in range(len(args)):
if idx != os:
total += args[idx]
print "adding test =", total

test_num_variables(1, 3, 5, None)``````

With Exceptions:

``````from __future__ import division, print_function
def solve(v=None, u=None, a=None, t=None):
try:
v = u + a*t
print('v')
except TypeError:
try:
u = v - a*t
print('u')
except TypeError:
try:
a = (v-u) / t
print('a')
except TypeError:
print('t')
t = (v-u) / a

assert v == u + a*t
return v, u, a, t

print(solve(4, 2, 2))
print(solve(u=3, a=3.5, t=2))``````

A variation on woooee's idea

``````def F1(v, u, a, t):
args = (v, u, a, t)
if args.count(None) != 1:
raise TypeError("Exactly one argument of F1() must be None")
index = args.index(None)``````

For completeness, you can also use a dictionary

``````def F1(*args):
if len(args) == 4:
to_dict ={}
to_dict["v"]=args[0]
to_dict["u"]=args[1]
to_dict["a"]=args[2]
to_dict["t"]=args[3]

for key in to_dict:
print key, to_dict[key]     ## while testing
if to_dict[key] == None:
## etc``````

thanks for all the suggestions you gave me to improve my code. I am quite new to python and programming in general and appreciate any help i can get. Thank you all for your quick responses

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.