简体   繁体   English

如何将用户输入转换为浮点数或整数?

[英]How do i convert user input to a float or int?

So I have所以我有

inp = print(input('what is your number?'))
n = float(inp) 
for i in range(1,n):
    print('the derivativ to the', n, 'derivative is', simplify(diff(f,x,i)))

and it says I cannot do this because my n is a n.netype val and not an int or float , but it wont let me convert to either of those它说我不能这样做,因为我的nn.netype val 而不是intfloat ,但它不会让我转换为其中任何一个

You're getting this error because you are assigning the return value of a print function, which is None , to inp .您收到此错误是因为您将打印 function 的返回值(即None )分配给inp Try this instead:试试这个:

inp = input('what is your number?')
print(inp)
n = float(inp) 
for i in range(1,n):
    print('the derivativ to the', n, 'derivative is', simplify(diff(f,x,i)))

Code below should work for you:下面的代码应该适合你:

n = int(input('what is your number?'))
for i in range(1,n):
    print('the derivativ to the', n, 'derivative is', simplify(diff(f,x,i)))

input returns a string which you have to explicitly convert to int, like this: input返回一个字符串,您必须将其显式转换为 int,如下所示:

n = int(input('what is your number?'))

As mentioned, you pass the number input to print and then use the result of print for your variable.如前所述,您将数字输入传递给print ,然后将print结果用于您的变量。 But print always returns None - you've lost the input.但是print总是返回None - 你丢失了输入。 Assign the variable and print in different steps.分配变量并分步打印。 But don't forget to manage errors.但不要忘记管理错误。 Users are notoriously bad at following instructions.众所周知,用户不善于遵循说明。

Notice also that float can't be used in the range function whose job is to emit integers.另请注意, float不能用于 function range ,其工作是发出整数。 Force the user input to be an integer from the get go to avoid errors.从 get go 强制用户输入为 integer 以避免错误。

while True:
    inp = input('what is your number?')
    print(inp)
    try:
        n = int(inp)
        if n <= 1:
            raise ValueError("Natural numbers greater than 1 only")
        break
    except ValueError as e:
        print(f"{e}. Try again.")

for i in range(1,n):
    print('the derivativ to the', n, 'derivative is', simplify(diff(f,x,i)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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