1,105,585 Community Members

Problem reassigning values to variables

Member Avatar
adrigreat14
Newbie Poster
2 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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')
Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
0
 

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.

Member Avatar
Gribouillis
Posting Maven
3,456 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
0
 

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.

Member Avatar
woooee
Posting Maven
2,798 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

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:
        print "None was not found"
        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)
Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

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))
Member Avatar
Gribouillis
Posting Maven
3,456 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
0
 

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)
Member Avatar
woooee
Posting Maven
2,798 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

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
Member Avatar
adrigreat14
Newbie Poster
2 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Question Answered as of 2 Years Ago by woooee, Gribouillis, snippsat and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: