简体   繁体   中英

how can i put input() function into a def fonction in python 3

I am working on a collatz sequence that i have found in a book and i want to input the number but it dosen t work , when i put the number the enter keybord key does not work , have i made something wrong in my program ? :

even = range(0,10**5,2)
odd = range(1,10**5,2)

def collatz_s(num):
    while num !=1 :
        if num in even :
            result = num /2
            print(result)
            num = result

        elif num is odd :
            result = num *3+1
            num = result
            print(result)


num = int(input('choose a random number'))
collatz_s(num)

To check whether a number is odd or even, rather than generating range objects and checking whether a number is in them, look at the remainder in the division by two, which you can get with num % 2 . If the remained is 1, it means the number is even. Otherwise, it's odd.

Also, use num // 2 to perform an integer division. That way dividing 16 by 2 will give you 8 (the integer number), instead of 8.0 (the floating point number.) It turns out this is really important here, especially since you're interested in finding the remainder of the division (a concept mainly concerning integer numbers.)

I believe it's quite possible that a rounding error in the floating point division might have put your program into an infinite loop (since a number with a tiny decimal part would not be in either even or odd range.) Or if you were surpassing the limit of your ranges (10 5 ) you'd be in the same situation where neither branch matches. Using integer division and checking for even or odd using the remainder should fix both issues.

def collatz_s(num):
    while num != 1:
        if num % 2 == 0:
            num = num // 2
            print(num)
        else:
            num = num * 3 + 1
            print(num)

The problem is within your elif block, here elif num is odd : change is to in when dealing with remainder use integer division(//) instead to avoid precision error .

def collatz_s(num):
    while num != 1:
        if num in even:
            result = num // 2
            print(result)
            num = result

        elif num in odd:
            result = num * 3 + 1
            print(result)
            num = result



num = int(input('choose a random number'))
collatz_s(num) 
# input 5
# output 

16
8
4
2
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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