Notes learning python "python programming quick start - let automate the tedious work" of the two

Problem two
to write a function named collatz (), which has a parameter named number. If the argument is an even number, then Collatz () to print out the number // 2, and returns the value. If the number is odd, collatz () to print and return 3 * number + 1. Then write a program that allows the user to enter an integer, and continue to call this number collatz (), until the function returns a value of 1 (Surprisingly, this sequence is valid for any integer, use this sequence, you will sooner or later get 1 ! even mathematicians can not determine why. your program in the study of so-called "Collatz sequence," it is sometimes called the "most simple, impossible math problem").

def collatz(number):#定义函数
	try:
		new_num=int(number)#判断num是否为正整数
	except:
		print('请输入正整数')#显示出错原因
	else:
		new_num=new_num%2#偶数余数为0,其他为奇数
		if not new_num: #偶数
			number=int(number)//2
		else:#奇数
			number=int(number)*3+1
	print(number)
	return number
# number=input('输入整数')
# nex=collatz(number)#初始赋值
#判断nex是否为整数并且不等于0
# if isinstance(nex,int)and int(number) != 0:
# 	while nex !=1:
# 		nex=collatz(nex)#循环赋值
Published 23 original articles · won praise 5 · Views 392

Guess you like

Origin blog.csdn.net/weixin_43287121/article/details/104478819