Python 中的条件处理

问题描述 投票:0回答:1

我编写的脚本有3个结果,它要么求解数字的阶乘,要么给出输入值不是正数的消息,或者给出不是数字的消息,但结果不是数字不起作用。

user_number_input = input('Insert number: ')#This asks the user to input a number.
uni_int = int(user_number_input)


if uni_int < 0: #This checks if the number is negative, it will print an error message.
        print('Not a positive number!')
elif uni_int > 0:
    
    factorial_value = 1 #This is to ensure the calculation starts at 1 and not 0.
    while uni_int > 1: #Multiply number_inserted until 1 (n! = n x (n-1) x (n-2)...x 2 x 1)
         factorial_value *= uni_int #This is where the multiplication takes place, eg: 5 * 5 - 1 * 5 - 2...
         uni_int -= 1 #This ensures we move closer to 1, like within the formula (n! = n x (n-1) x (n-2)...x 2 x 1)<--- 1 is the end.
    print(factorial_value)
elif user_number_input != int and user_number_input == ' ':
   print('Not a number!')

我尝试重新排列代码,以便第一个条件将检查该值是否不是数字,但最后一个条件不起作用,这将检查该值是否为正数。

python math conditional-statements integer output
1个回答
0
投票

当第二行输入“s12”时,您将遇到 ValueError 。为了避免这个问题,请使用 try - except 首先尝试您的输入是否可以转换为 int 。如果不是,你的输出将是“不是数字”,如果可以转换为 int 那么将遵循其他语句。

user_number_input = input('Insert number: ')#This asks the user to input a number.

try:
    uni_int = int(user_number_input)

    if uni_int < 0: #This checks if the number is negative, it will print an error message.
            print('Not a positive number!')
    elif uni_int > 0:
        
        factorial_value = 1 #This is to ensure the calculation starts at 1 and not 0.
        while uni_int > 1: #Multiply number_inserted until 1 (n! = n x (n-1) x (n-2)...x 2 x 1)
            factorial_value *= uni_int #This is where the multiplication takes place, eg: 5 * 5 - 1 * 5 - 2...
            uni_int -= 1 #This ensures we move closer to 1, like within the formula (n! = n x (n-1) x (n-2)...x 2 x 1)<--- 1 is the end.
        print(factorial_value)

except: 
   print('Not a number!')
© www.soinside.com 2019 - 2024. All rights reserved.