简体   繁体   中英

How do I code this python inputs conditions?

Build a function named “multiply” that accepts two user “inputs” when run.

As a user, when I run your function, I should be asked to input the first value I want to multiply, and then the second value.

If any of my inputs are non-numbers (ie: inputs should be either floats or integers), then the function should return “Error: invalid argument!”

Else, the function should return the product of the two inputs.

def multiply ():
     num1 = (input('Multiply '))
     num2 = (input ('by '))
if num1 == int:
    return "error: invalid error"
else:
    print ("int()")
else:
    num1 = float(input('Multiply '))
    num2 = float(input('by '))
    product = (num1*num2)
    return product

Using Python3 you could do something like this:

import sys

def multiply () -> float:
    num1:float = float(input('Multiply '))
    num2:float = float(input ('by '))
    if not isinstance(num1, float) and not isinstance(num2, float):
        return ValueError("error: invalid error")
    return num1 * num2


print(multiply())

Will accept both ints and floats. But will return float as you can see by the functions return signature.

Or if you want the user to be continually asked until they provide correct floats or integer-values.

def multiply () -> float:
    num1:float
    num2:float
    err = False
    while(not err):
        err = True
        try:
            num1 = float(input('Multiply '))
            num2 = float(input ('by '))
        except ValueError:
            print("You did not input a float value... Try again")
            err = False
    return float(num1) * float(num2)

print(multiply())

Try this below:

def multiply():
    num1 = (input('Multiply '))
    num2 = (input('by '))

    if not num1.isdigit() or not num2.isdigit():
        return "error: invalid error"
    else:
        num1 = float(num1)
        num2 = float(num2)
        product = (num1 * num2)
        return product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM