如何在Python中跳转到某一行?

0 投票
3 回答
44380 浏览
提问于 2025-04-16 08:43

我想知道有没有什么命令可以让我直接跳到某一行,而不需要看其他行,类似下面这样的:

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'

3 个回答

-1

如果你只是想调试代码,我觉得最简单的方法就是暂时把那些不想执行的代码行注释掉。你只需要在想跳过的每一行前面加上#就可以了。

if [x] in database1:
     code to execute

# code to skip

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

在Python中替代GOTO功能的最佳示例

def L1():

    a = 10

    print(a)

def L2():

    b = 100

    print(b)

var = str(input("Give your choice, True, False?"))

if var == 'True':
   L1()

else :

    L2()

4

不,这种命令是不存在的。它被称为 goto,而且几乎只出现在非常早期的编程语言中。其实它是 完全不必要 的:你总是可以通过结合使用 ifwhile(或者在Python中更常用的 for)来实现相同的效果,而且很多人认为它是 有害的

之所以经常被滥用,是因为它让程序的执行流程变得难以理解。当你阅读一个正常的(结构化的)程序时,很容易看出控制会流向哪里:要么是一个 while 循环,要么是进入一个方法调用,或者根据条件进行分支。然而,当你阅读一个使用 goto 的程序时,控制可能会在程序中任意跳跃。

在你的情况下,你可以把所有中间的代码放在一个条件语句里,或者把第二行重构成一个单独的函数:

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

(顺便问一下,你确定你是想说 [x] in database1 而不是 x in database1 吗?)


编辑:这是你放在 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!'

撰写回答