简体   繁体   中英

How do I add a loop to my python code, to start it from the beginning?

How can I make this restart from the beginning if they select Yes (y)

print ""
print "               WAGE CALCULATOR TOOL   -    By Joel"
print""
print " Please enter details: "
name = raw_input("  Employee Name: ")
hrs = float(raw_input("  Hours Per Week: "))
rate = float(raw_input("  Hourly Rate: "))
pay = hrs * rate
print ""
print "",name,":","Wage amount: "
print " ",pay,"Per week"
week = pay * 4
print " ",week,"Every 4 weeks"
print""

done = raw_input("Restart? y/n: )

It would suggest wrapping this into a function:

def ask():
    print " Please enter details: "
    name = raw_input("  Employee Name: ")
    hrs = float(raw_input("  Hours Per Week: "))
    rate = float(raw_input("  Hourly Rate: "))
    pay = hrs * rate
    print ""
    print "",name,":","Wage amount: "
    print " ",pay,"Per week"
    week = pay * 4
    print " ",week,"Every 4 weeks"
    print""

    return raw_input("Restart? y/n: ") == "y"

done = ask()
while not done:
    done = ask()

Of course you should also consider validating the user input (eg catch the errors thrown by float() by try/except ).

def ask():
    print (" Please enter details: ")
    name = input("  Employee Name: ")
    hrs = float(input("  Hours Per Week: ")
    rate = float(input("  Hourly Rate: ")
    pay = hrs * rate
    print ("")
    print (""),name,(":"),("Wage amount: ")
    print (" "),pay,("Per week")
    week = pay * 4
    print (" "),week,("Every 4 weeks")
    print("")

    return input("Restart? y/n: ") == "y"

done = ask()
while not done:
    done = ask()

I tried no raw input and it seems to have worked better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM