Collat​​z序列:使用Python第3章练习项目自动化无聊的东西

时间:2016-02-02 05:47:35

标签: python

这是我的工作代码:

number = int(input())
while number > 1:
    if number % 2 == 0:
        number = int(number) // 2
        print (number)
    elif number % 2 == 1:
        number = 3 * int(number) + 1
        print (number)

现在我试图添加一个例外,如果用户输入有非整数值,它应该打印'输入一个数字'

7 个答案:

答案 0 :(得分:1)

while True:
    try:
        number = int(raw_input())
        break
    except ValueError:
        print("Enter a number!")
while number > 1:
    ....

编辑:如Anton的评论中所述,在Python 2中使用raw_input,在Python 3中使用input

答案 1 :(得分:1)

我是一个完全的初学者,所以我会很感激各种提示。以下是我设法解决问题的方法,现在似乎工作正常:

def collatz(number):
    
    if number%2 == 0:
        return number // 2
    else:
        return 3*number+1
        
print ('Enter a number:')

try:
    number = int(input())

    while True:            
            if collatz(number) != 1:
                number= collatz(number)
                print(number)
            else:
                print('Success!')
                break        
except ValueError:
    print('Type an integer, please.')

答案 2 :(得分:0)

您可以检查ValueError的{​​{1}}。来自docs

  

例外 except   当内置操作或函数接收到具有正确类型但值不合适的参数的情况时引发,并且情况不会由更准确的异常(如IndexError)描述。

ValueError

答案 3 :(得分:0)

你可以这样做 -

 while number != 1:
    try:
        if number % 2 == 0:
           number = int(number) // 2
           print (number)
        elif number % 2 == 1:
           number = 3 * int(number) + 1
           print (number)
     except ValueError:
        print('Enter a number')
        break

答案 4 :(得分:0)

def collatz(number):
    if number % 2 == 0:
        return number // 2
    else:
        return 3 * number + 1

while True:
    try:
        value = int(input("Eneter a number: "))
        break
    except ValueError:
        print("enter a valid integer!")


while value != 1:
    print(collatz(value))
    value = collatz(value)

答案 5 :(得分:0)

def coll(number):

    while number !=1:
        if number%2==0:
            number= number//2
            print(number)

        else:
            number= 3*number+1
            print(number)
while True:
    try:
        number = int(input("Enter the no:"))
        break
    except ValueError:
        print("Enter a number")


print(coll(number))

答案 6 :(得分:0)

我是这样做的:

# My fuction (MINI-Program)
def collatz(number):
    if number % 2 == 0:
        return number // 2
    else:
        return 3 * number + 1
# try & except clause for errors for non integers from the users input
try:
    userInput = int(input("Enter a number: "))
    # Main loops till we get to the number 1
    while True:
        number = collatz(userInput)
        if number !=1:
            userInput = number
            print(userInput)
        else:
            print(1)
            break
except ValueError:
    print("Numbers only! Restart program")