如何在Python中跳转到行?

时间:2010-12-19 00:13:05

标签: python

我想知道是否有一个命令可以帮助我转到特定的行并跳过其他行,如下所示:

if [x] in database1: (the command I need)

skipping other lines.......
to go here:

if [x] in database1: print ' Thank you ' + name + ' :)\n'  <<<< which is in line 31 

编辑:从pastebin

添加了代码
print ' Note: Write your Name and Surname with the first leter, BIG !'
print ' ...'

name = raw_input('Name: ')
surname = raw_input('Surname: ')

print name + ' ' + surname + ',' + ' The Great !\n'

print ' Did you like this ?'

x = raw_input('Yes/No : ')
print ''

database = [
    ['No'],
    ['no']
]
database1 = [
    ['Yes'],
    ['yes']
]
if [x] in database: print ' Did you really meant that ?'
if [x] in database: y = raw_input('Yes/No : ')

# (I need the command here to go that line :)


if [y] in database1: print ' So you'll be dead ' + name + ' !\n'
if [y] in database: print ' Oh OK, Than your free to go ' + name + ' :)'

if [x] in database1: print ' Thank you ' + name + ' :)\n'
if [x] in database1: print 'Try (No) next time !\n'

4 个答案:

答案 0 :(得分:3)

不,没有这样的命令。它被称为goto,几乎只出现在早期的编程语言中。它是never necessary:您可以使用ifwhile(或更多Python,for)和considered harmful的组合来实现相同的效果许多。

它被滥用的原因是它使程序的流程难以遵循。当读取正常(结构化)程序时,很容易分辨控制将在何处流动:围绕while循环,进入方法调用或按条件分割。但是,当使用goto读取程序时,控件可以在程序周围任意跳转。

在您的情况下,您可以将所有中间行包含在条件内,或者将第二行重构为单独的函数:

def thank(x, name):
    if [x] in database1:
        print 'Thank you, {0}:\n'.format(name)

(P.S。你确定你的意思是[x] in database1而不是x in database1吗?)


编辑:以下是您在your pastebin中添加的代码的编辑版本:

print 'Enter your name and surname:'

# `.title()` makes first letter capital and rest lowercase
name = raw_input('Name: ').title()
surname = raw_input('Surname: ').title()

# use `.format(...)` to create fancy strings
print '{name} {surname}, the Great!'.format(name=name, surname=surname)

noes = ['no', 'n']
yesses = ['yes', 'y']

print 'Did you like this?'

# `.lower()` for lowercase
if raw_input('Yes/No: ').lower() in noes:
    print 'Did you really mean that?'
    if raw_input('Yes/No : ') in yesses: 
        print 'So you\'ll be dead, {name}!'.format(name=name)
    else:
        print 'Oh, OK, then you\'re free to go, {name}.'.format(name=name)
else:
    print 'Thank you, {name}.'.format(name=name)
    print 'Try "no" next time!'

答案 1 :(得分:1)

this library允许在Python中使用goto,但请不要使用它。

答案 2 :(得分:0)

如果您只是调试,我认为跳过行的最简单方法是暂时注释掉这些行。只需在要跳过的所有行的开头添加#即可。

if [x] in database1:
     code to execute

# code to skip

if [x] in database1: print ' Thank you ' + name + ' :)\n'

答案 3 :(得分:0)

在Python中替代GOTO函数的最佳示例

def L1():

a = 10

print(a)

def L2():

b = 100

print(b)

var = str(input(“给出选择,对,对吗?”))

如果var =='True': L1()

其他:

L2()