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

  • 本文关键字:问题 代码 其他 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")    

如果您将其放入一个小列表并对其进行排序,则逻辑可能会变得更容易:

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")

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])) 

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

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

最新更新