We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,376 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Problem reassigning values to variables

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')
5
Contributors
7
Replies
1 Week
Discussion Span
1 Year Ago
Last Updated
8
Views
Question
Answered
adrigreat14
Newbie Poster
2 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.

snippsat
Posting Shark
957 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

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.

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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)
woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9

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))
pyTony
pyMod
Moderator
6,312 posts since Apr 2010
Reputation Points: 879
Solved Threads: 987
Skill Endorsements: 26

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)
Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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
woooee
Posting Maven
2,707 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9

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

adrigreat14
Newbie Poster
2 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by Gribouillis, woooee, snippsat and 1 other

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0833 seconds using 2.73MB