蟒蛇。结果不正确

时间:2017-09-07 18:18:00

标签: python

我是一个相当新的python初学者。我用子程序编写了一个代码来查找最大数字和最小数字以及数字之间的范围。 然而,当我试图找到最大数量,最小数量甚至范围时,我的测试数据的答案出错了。测试数据x = 12,y = 6,z = 2表示最大数字是y。< / p>

注意:变量是output1,用于选择1打印,依此类推

x = input("Enter x:")
y = input("Enter y:")
z = input("Enter z:")
if x>y and x>z :
    output1 = 'x is the largest'
    large = x
elif (y>x and y>z):
    output1 = 'y is the largest'
    large = y
elif (z>x and z>y):
    output1 = 'z is the largest'
    large = z
else :
    output1 ='all numbers are equal'
    large = 0
if x<y and x<z :
    output2 = 'x is the smallest'
    small = x
elif (y<x and y<z):
    output2 = 'y is the smallest'
    small = y
elif (z<x and z<y):
    output2 = 'z is the smallest'
    small = z
else :
    output2 = 'all numbers are equal'
    small = 0
output3 = large-small
outputq = "Bye" 
print("[1] Find the highest variable.")
print("[2] Find the lowest variable.")
print("[3] Find the range between the highest and the lowest variables.")
print("[q] Quit.")
while outputq == ('Bye'):
    choice = input("Enter choice number:")
    if choice == '1'   :print (output1)
    elif choice == '2' :print (output2)
    elif choice == '3' :print (output3)
    elif choice == 'q' :
        print (outputq)
        outputq="end"
    input ()

2 个答案:

答案 0 :(得分:1)

代码中的

if x>y and x>z :比较字符串而不是数字,因为input()返回字符串。将其转换为int:

x = int(input("Enter x:"))
y = int(input("Enter y:"))
z = int(input("Enter z:"))

答案 1 :(得分:0)

我重构了你的代码并分成了函数

首先找到最大的

def find_largest(data):
    x, y, z = data
    print('\nx = {}, y = {}, z = {}'.format(x,y,z))

    a=''
    if x>y and x>z :
        a = 'x is the largest'
    elif (y>z):
        a = 'y is the largest'
    else:
        a = 'z is the largest'

    return a

找到最低

def find_lowest(data):
    x, y, z = data
    print('\nx = {}, y = {}, z = {}'.format(x,y,z))

    b = ''
    if x<y and x<z :
        b = 'x is the smallest'
    elif (y<z):
        b = 'y is the smallest'
    else:
        b = 'z is the smallest'

    return b

查找中等范围

def find_mid(data):
    return (max(data)-min(data))

最终,代码段

data = [12,6,2] # used list to pass data
print("[1] Find the highest variable.")
print("[2] Find the lowest variable.")
print("[3] Find the range between the highest and the lowest variables.")
print("[q] Quit.")
d = ''
while d != 'Bye':
    choice = input("Enter choice number:")
    if choice == '1'   :
        print (find_largest(data))
    elif choice == '2' :
        print (find_lowest(data))
    elif choice == '3' :
        print (find_mid(data))
    elif choice == 'q' :
        d = 'Bye'
        print(d)

检查以下链接上的工作代码

Find Largest/lowest and mid

此链接将帮助您了解代码的流程。单击前进按钮以了解步骤。