python - 脚本返回思路
高洛峰
高洛峰 2017-04-17 11:24:32
0
4
512

新手刚学习编程,请大家给点思路,我写了个roll点的脚本,现在想让脚本在输入错误的的时候重新返回到第一步,不知道从哪里下手

https://gist.github.com/chengxiao/5393578

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
PHPzhong

Looking at your program, I feel like I saw myself many years ago... After hesitating for a long time, I decided to write this answer...

@greatghoul's answer was chosen as the best but it's not actually a good answer...

Call itself inside a function to return to the beginning... From a programming perspective, this is a behavior that simulates goto...

But in fact this simulation is not as good as goto... because it is a recursion... The program will error after a certain number of input errors...

A good program should be structured... there are incomings and outgoings... so I probably changed it a bit... as follows...

# today my lucky number
from random import choice

def roll( x, y ):
    return choice( range( x, y ) )

def controller():
    a = raw_input( "Please enter /roll + number : " )

    try:
        if "/roll" == a:
            x, y  = 0, 100
        elif "-" in a:
            b = a.split()[1].split( "-" )
            x, y = int( b[0] ), int( b[1] );
            if ( x > y ) : x, y = y, x
            ++ y
        else:
            x, y = 0, int( a.split()[1] )

        print "Today Your Lucky Number Is %s" % roll( x, y )
        raw_input( "Enter anykey to Exit !" )
        return 1

    except ( ValueError, IndexError ):
        return 0

while not controller():
    print "Sorry,Please Enter /roll + number"

The idea is very clear...the action of repeatedly calling a function occurs outside the function...controlled by the return value of the function...

I wrote GWBasic when I was very young... the only process control was goto... there was no way around it...

Nowadays, programming languages ​​and programming ideas have developed greatly... In the past ten years, no one has used goto anymore... You can't fall behind, right...?

In addition, let me ask another question... Have you noticed that you have done a lot of repetitive work?

There are various split in the program... Various choice... Exactly the same except The logic is written twice...

Even the output content has been typed many times... Have you ever thought about using good program structure to reduce your input...?

While reading my above example code, also think about this issue... If you don’t understand, feel free to ask... Don’t just focus on the loop...

That’s it...

洪涛

Wrap it into a function and call it again when an error occurs.

# today my lucky number
from random  import choice

def rollit():
    a =raw_input("Please enter /roll + number :")

    if a.startswith("/roll") :
        if a == "/roll":
            print "Today Your Lucky Number Is  %s"% roll(100)
            raw_input("Enter anykey to Exit !")
        elif "-" in a:
            try:
                b = a.split(" ")[1]
                c =b.replace("-"," ").split()[0]
                d =b.replace("-"," ").split()[1]
                if int(c)>int(d):
                    print choice(range(int(d),int(c)+1))
                elif int(c)<int(d):
                    print choice(range(int(c),int(d)+1))
            except ValueError:
                print "Sorry,Please Enter /roll + number"
                raw_input("Enter anykey to Exit !")
        else:
            try:
                b = a.split(" ")[1]
                c = int(b)
                print "Today Your Lucky Number Is  %s"% roll(c)
                raw_input("Enter anykey to Exit !")
            except ValueError:
                print "Sorry,Please Enter /roll + number"
                raw_input("Enter anykey to Exit !")


    else:
        print "Sorry,Please Enter /roll + number!"
        rollit()

def roll(c):
    y = choice(range(c))
    return  y

rollit()
Peter_Zhu

Put the entire program into a loop
Enter correctly -> Jump out of the loop and the program ends
Input error -> Execute loop, program continues

刘奇

My first reaction was to use recursion

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template