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.)
'''Enter 3 values using None for the missing one to calc using v=u+at'''
for i in ('v','u','a','t'):
if type(vars()[i])== type(1) or type(vars()[i])==type(0.1):
## elif type(vars()[i])!= type(None):
## print('Error, Wrong input type entered')
## return 'Error'
## if numVars<3:
## return None
## elif numVars==4:
## if vtrue==False:
## if utrue==False:
## if atrue==False:
## if ttrue==False:
## print('No answer found')
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.
number = float(input('Enter a number: '))
print('val correct %s' % number)
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)
print('%s is not number' % item)
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.
Receive the variables as a tuple and then use each item as your variable.
print "number of variables =", args, type(args), len(args)
os = -1
if None in args:
print "finding None =", os, args[os]
print "None was not found"
## 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)
from __future__ import division, print_function
def solve(v=None, u=None, a=None, t=None):
v = u + a*t
u = v - a*t
a = (v-u) / 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))