繁体   English   中英

Python - 如果插入的值是浮点数或负数,我如何使此代码工作?

[英]Python - How do i make this code work if inserted value is float or negative?

如果用户输入 -777 或 77.1 我如何使程序工作而不是说输入的数字是字符串?

主文件

from  helper import *

def main():
#  menu 
    user_selection = ""
    while user_selection != "x":
        print("a - Input something")
        print("x - exit")
        # get the user selection
        user_selection = input("select an option: ")
        print("The user select: "+user_selection)
        # implement the user selection
        if user_selection == "a":
            input_analyst()
            break
       

if __name__ == "__main__":
    main()

帮助文件

from os.path import exists
from tracemalloc import stop


# this was done purely by hand and google was never used so it might not be size-effective
def input_analyst():

    user_input = input("your input: ")
    # Return True if the string is a numeric string, False otherwise.
    if user_input.isnumeric():
        print("Entered user_input is Integer:", user_input)
        num = int(user_input)  # if its an int set num as the inputed value

    else:
        # if the inputed data is a string print so and stop the function
        print("Entered user_input is a string")
        return

    if user_input.isnumeric():  # if its a int display it's lengh
        print("The int lengh is: ", len(user_input))

    if (num % 2) == 0:  # check if the number is even or odd
        print("{} is an Even number".format(num))
    else:
        print("{} is an Odd number".format(num))

    if num % 7 == 0:  # check if the number is dividable by 7 without a remainder or not and prints how much it would actually be if Divided by 7
        number1 = num
        number2 = 7
        result = number1/number2
        print("{} Dividable by 7 without a remainder".format(num))
        print("{} Dividable by 7 =: {} ".format(num, result))

    else:
        number1 = num
        number2 = 7
        result = number1/number2
        print("{} Isn't dividable by 7 without a remainder".format(num))
        print("{} Divided by 7 =: {} ".format(num, result))

如果用户输入 -777 或 77.1 我如何使程序工作而不是说输入的数字是字符串?

您可以使用转换与 try / 一起浮动,除了:

try:
    num = int(float(user_input))
    print("Entered user input is Integer:", user_input)

except ValueError:
    print("Entered user_input is a string")
    return

在这种情况下,您还将接受“-77.5”之类的内容作为 integer (-77)。 如果您不希望这样,可以添加支票:

int(float(user_input)) == float(user_input) 

现在有人可能会说没有必要将中间转换为浮点数,但从您的问题来看,您似乎也想接受像77.0这样的东西作为整数。

您将在您称为帮助文件的input()级别执行此操作。

所以这样的事情会起作用:


user_input = input("your input: ")

# first convert to an int
user_input = int(user_input)

if user_input <0:
    # some logic
    print('warning, negative number, convert to positive')
    user_input = -user_input

print(user_input)

暂无
暂无

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

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