[英]How do I code this python inputs conditions?
Build a function named “multiply” that accepts two user “inputs” when run.构建一个名为“multiply”的函数,该函数在运行时接受两个用户“输入”。
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:使用 Python3 你可以做这样的事情:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.