0

I was working on some simple code in python for getting input from a user as part of a triangle solver. The solution I went with ended up having this code three times (but with b and c instead of a):

while True:

        var = input()
        
        try:
        
            a = float(var)
            break

        except ValueError: print("That is not a number! Try again!")

What I wanted to do was do something similar to this:

def getSide(side)

    while True:

        var = input()
        
        try:
        
            side = float(var)
            break

        except ValueError: print("That is not a number! Try again!")

With the idea of calling the function creating and setting a variable to the user input (i.e. getSide(number) would create a float number that was equal to the number the user input). This ultimately did not work and the work around I used was this:

def getSide():  

    while True:

        global var
        var = input() 
        print(var)
        
        try:
            
            var = float(var)
            break

        except ValueError: print("That is not a number! Try again!") #If user inputs a string

getSide()
a = var    

My question is, is there a way for me to do what I had originally wanted to do? Is there a way to define a function that creates different variables using arguments?

Tyler
  • 11
  • 1

1 Answers1

1

Simply return the value from your function. The Python tutorial goes over return values here.

def get_number(prompt):
    while True:
        var = input(prompt)
        try:
            return float(var)
        except ValueError:
            print("That is not a number! Try again!")


a = get_number("Enter number A:")
b = get_number("Enter number B:")
AKX
  • 152,115
  • 15
  • 115
  • 172