在Python中创建方法

时间:2018-10-11 16:27:22

标签: python methods

我正在尝试在python中创建一个可以在以后调用的方法,但是当我运行代码时,它不再起作用。 (在尝试将其变成方法之前,代码已经起作用了)我并不是在试图创建一个类或其他任何花哨的东西,而只是试图获得一个可以调用的有效方法。没有显示错误,程序无法正常运行。

我对Python编程还很陌生,感谢您的帮助

def func():
x= int(input())
while (x>1):
    if x%2 == 0:
        x = x//2
        print(x)
    elif x%2 != 0:
        x= x*3+1
        print(x)
func()

请客气,让我知道是否可以澄清任何事情。

4 个答案:

答案 0 :(得分:1)

您的缩进是错误的。请始终使用空格或制表符。

<!doctype html>

<html>

<head>
	<link rel="stylesheet" href="lib/style.css">
	<script src="lib/script.js">

	</script>
</head>

<body>
	<div class="flex-layout" role="heading">
		<div class="toolbar-header rectangle-mask"></div>
		<div class="toolbar-header circle-mask">
			<img class="picture" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAP1BMVEWtra3x8fGqqqr09PTw8PCoqKiysrLq6uqvr6/U1NS2trbd3d3n5+e6urrj4+PZ2dnAwMDGxsbNzc3KysrDw8PDHe7TAAAINUlEQVR4nO2d2bqrIAyFrTjPtX3/Zz3a1q0ijlmJxdN12Zv6f4GEBAjO7epyzv4Adv0I7deP0H79CO3Xj9B+/QjRUq1E/1GIsOXysiJNy7JM0yLz5EAFCBuUIr4njjuUk9zj4iZByU2ovKLOX0i62h/zuvC4KVkJlZc+IxPdADN6ph4rIyOhyh7BEt0fZPDIGBnZCFVRbcDrIKuCjZGJUBW5v5XvJT/nYmQhVFm1C+9tyIpnrDIQKu+xeXyOEJ0Hh8/BE6o0OML3YgxSPCKaUKn7Ub4X4x2OCCZUWUIBbBAT9GzEEqqUhPdWiUWEEqqaZsC33BqKiCSkTcEBInQyIgkPBMEZxAr4VThCDwaIRcQRPnGADeITNlBRhAoKiEQEEarahwICPSqGUJVYC74QQXERQqgyOF8rzOoGQugRl2ozSjzExyEIUZFeFybyAwh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XmcajhP9nvDsr4IqNBCG15mG4ztRHaH9VbahhkvTP8IrFDB6DUoZf4RXWZR+5E0IpZ6jFJJfTAgvUaLpNSjWONeL960GxZqO0P5y/liRTij2eLGU/FAjzM7+IrT6mP8mvEoRqle/ffEhvEQteKRKI7yaoxm4Gueajsbp8/w3IeMDf2fpz9U413Q0A1fjXNTR9O+V/wNd2n/T4a0ndgAAAABJRU5ErkJggg==" alt="Header picture"/>
		</div>
</div>

  </body>
</html>

答案 1 :(得分:0)

我不知道这是否只是这里的格式,但是您在方法内部正确缩进了吗? 应该是:

def func():
    x= int(input())
    while (x > 1):
        if x % 2 == 0:
            x = x // 2
            print(x)
        elif x % 2 != 0:
            x= x * 3 + 1
            print(x)

如果不是这种情况,请告诉我们您尝试运行时遇到什么错误?

答案 2 :(得分:0)

您需要稍微更改缩进

def func():
    x= int(input())
    while (x>1):
        if x%2 == 0:
            x = x//2
            print(x)
        else:
            x= x*3+1
            print(x)

当我在Jupyter Notebook中运行时

func()
2
1

从以下位置安装Jupyter jupyter

答案 3 :(得分:-1)

您需要添加缩进,我更喜欢在功能之外使用输入。

然后,您可以重用函数逻辑。

当然这取决于您的情况。

def func(x):
    while (x>1):
        if x%2 == 0:
            x = x//2
            print(x)
        elif x%2 != 0:
            x= x*3+1
            print(x)

x= int(input())
func(x)