需要帮助来编写比较函数

时间:2015-03-31 06:20:04

标签: python

需要帮助将该程序的比较部分编写为函数

import random
import sys

def myScript():

    ett = random.randint (1, 100)
    tva = random.randint (1, 100)

    print ("tal1", ett, "\n""tal2", tva)

    if (ett > tva):
        print ("tal1 är störst")
    elif (tva > ett):
        print ("tal2 är störst")
    else:
        print("talen är lika stora")       

    print ("vill du testa igen y/n")
    yes = set(['y'])
    no = set(['n'])

    choice = input().lower()
    if choice in yes:
        myScript()
    elif choice in no:
        sys.exit()
    else:
        sys.stdout.write("Please respond with 'y' or 'n'")
    myScript()

myScript()

2 个答案:

答案 0 :(得分:1)

我认为你需要compare part作为一种功能。

def my_compare(n, m):
   if cmp(n, m) == 1:
       return "tal1 är störst"
   elif cmp(n, m) == -1:
       return "tal2 är störst"
   else:
       return "talen är lika stora"

现在在你的程序中使用它,如

print(my_compare(ett, tva))

答案 1 :(得分:0)

喜欢这个?我只是将比较分解为一个单独的函数,并停止了建立调用堆栈的递归。

import random
import sys

def mycompare(ett, tva):
    if (ett > tva):
        print ("tal1 är störst")
    elif (tva > ett):
        print ("tal2 är störst")
    else:
        print("talen är lika stora")

def myScript():

    ett = random.randint (1, 100)
    tva = random.randint (1, 100)

    print ("tal1", ett, "\n""tal2", tva)
    mycompare(ett, tva)

    print ("vill du testa igen y/n")
    yes = 'y'
    no = 'n'

    while True:
        choice = input().lower()
        if choice == yes:
            return True
        elif choice == no:
            return False
        else:
            sys.stdout.write("Please respond with 'y' or 'n'")


if __name__ == '__main__':
    while myScript():
        pass
相关问题