此代码中的第5行有什么问题?其他线路有什么问题吗?

时间:2019-04-10 20:51:19

标签: python python-3.x

我刚刚开始学习python。我从学校有一些C ++的经验。问题是编写代码来打印用户输入中最大的奇数,如果没有奇数,则打印相关的反馈。这段代码有什么问题,还有解决此问题的更好方法吗?

#To print the largest odd number 

x = input ("Enter first number: ")
y = input ("Enter second number: ")
z = input ("Enter third number: ")

if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:
    print ("There are no odd numbers")

    if x % 2 != 0 and x > y and x > z:
        print (x, " is the largest odd number")

    if y % 2 != 0 and y > x and y > z:
        print (y, " is the largest odd number")

    if z % 2 != 0 and z > x and z > y:
        print (z, " is the largest odd number")

elif x == y == z:
    print ("All the numbers have the same value")    

3 个答案:

答案 0 :(得分:1)

如果将其放入一个小的列表并对其进行排序,也许逻辑会变得更容易:

x = input ("Enter first number: ")
y = input ("Enter second number: ")
z = input ("Enter third number: ")

odds = sorted([ i for i in [x,y,z] if int(i)%2 ],reverse=True)
if not odds:
    print("No odd number")
elif odds.count(odds[0]) == len(odds):
    print("All odd numbers are equal")
else:
    print(f"{odds[0]} is the largest odd number")

答案 1 :(得分:0)

2件事情:1.转换数据。 2.从外观上看,您的代码格式不正确。

对于1:

x = int(input(("Enter first number: ")) #Do this for y and z

对于2-,如果最大奇数小于最大偶数,则您的代码将永远不会返回最大奇数。例如[20、9、5]。要解决此问题:

#Create a list to work with
num_li = [x,y,z]

#Get all the odd numbers    
num_li = [i for i in num_li if i%2!=0]

#If no odd numbers
if len(num_li) == 0:
    print('No odds')
#Print the largest odd number
else:
    num_li.sort(reverse = True)
    print('The largest odd number is: ' + str(num_li[0])) 

答案 2 :(得分:0)

当前版本的代码有两个问题:

1)TypeError-您正在接收字符串作为输入并将其视为整数

2)逻辑错误-您的情况未涵盖所有情况。

我重写了代码。字符串将转换为int并涵盖所有情况。

工作示例:

x = int(input ("Enter first number: "))
y = int(input ("Enter second number: "))
z = int(input ("Enter third number: "))

numbers = [x, y, z]
odd_numbers = []
for number in numbers: // loop through the numbers and create an odd number list
  if number % 2 != 0:
    odd_numbers.append(number)

if odd_numbers: //print out the largest number in the list using max()
  print(max(odd_numbers))
else:
  print("No odd numbers")// if the list is empty this will be printed