简体   繁体   English

我如何完成这个功能?

[英]How do I complete this function?

For your assignment you must write a compare function that returns 1 if a > b , 0 if a == b , and -1 if a < b .对于您的作业,您必须编写一个比较函数,如果 a > b 返回 1,如果 a == b 返回 0,如果 a < b 返回 -1。 The user must be prompted for the values of a and b.必须提示用户输入 a 和 b 的值。 The compare function must have arguments for a and b.比较函数必须有 a 和 b 的参数。 To demonstrate your compare function, you must call the compare function three times, once for each condition, from within your program and display (using print statement) the return code of the function.为了演示您的比较函数,您必须在程序中调用比较函数三次,每个条件调用一次,并显示(使用打印语句)该函数的返回代码。

This is what I have so far...这是我到目前为止...

#-----define the compare function
def compare(a,b):
    if (a == b):
        return 0
    elif (a > b):
        return 1
    else:
        return -1

What do I do next?我接下来该怎么做?

For asking user for an input用于要求用户输入

  • Use input function if you are using Python 3如果您使用的是 Python 3,请使用input函数
  • Use raw_input function for Python 2.x在 Python 2.x 中使用raw_input函数

Convert the input into integer since the input values will be string.将输入转换为整数,因为输入值将是字符串。

Then call the compare function and get the value returned from compare function into variable and print it.然后调用compare函数,将compare函数返回的值放入变量中并打印出来。

def compare(a,b):
    if (a == b):
        return 0
    elif (a > b):
        return 1
    else:
        return -1

x=input("Enter first number :")
y=input("Enter first number :")
z=compare(int(x),int(y))
print(z)

I hope this will be helpful.我希望这会有所帮助。

Here is a menu driven solution that will run three times as desired.这是一个菜单驱动的解决方案,可根据需要运行 3 次。

   def compare(a,b):
    if (a == b):
        return 0
    elif (a > b):
        return 1
    else:
        return -1

counter =0
while counter < 3:    
    response=raw_input("Enter a Value for a and b [e.g. (4,5) ] : ")
    a , b = str(response).split(",")
    result = compare(a,b)
    print result
    counter += 1

Output:输出:

   Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Enter a Value for a and b [e.g. (4,5) ]: 4,5
-1
Enter a Value for a and b [e.g. (4,5) ]: 5,4
1
Enter a Value for a and b [e.g. (4,5) ]: 5,5
0
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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