初学者 Python 代码问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31256648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:42:36  来源:igfitidea点击:

Beginner Python Code Issues

python

提问by REDDY

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.

5.2 编写一个程序,反复提示用户输入整数,直到用户输入“完成”。输入“完成”后,打印出最大和最小的数字。如果用户输入的不是有效数字的任何内容,则使用 try/except 捕获它并发出适当的消息并忽略该数字。输入书中问题 5.1 的数字并匹配所需的输出,如图所示。

Here is my Code:

这是我的代码:

largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = float(inp)
    except:
        print "Invalid input"
    if smallest is None:
        smallest = num
    elif num < smallest:
        smallest = num
    elif num > largest:
        largest = num

    continue

print "Maximum is", largest
print "Minimum is", smallest

******Please let me know the Logic errors in this CODE*****

******请让我知道此代码中的逻辑错误*****

回答by NightShadeQueen

A: You never assign largest away from being None.

答:你永远不会分配最大的远离 None 。

B: On the case that float(inp) fails, you still try to continue on. You shouldn't. While you canmove those if/elif statements into the try block, I'd recommend against that, because you then run the risk of accidentally catching something you shouldn't. Instead, use try/except's much neglected elseblock.

B:在 float(inp) 失败的情况下,您仍然尝试继续。你不应该。虽然您可以将那些 if/elif 语句移到 try 块中,但我建议您不要这样做,因为您可能会冒着意外捕获不应该捕获的内容的风险。相反,使用 try/except 被忽视的else块。

In the same line, it's good practice only except the error you want to and not all errors.

在同一行中,除了您想要的错误而不是所有错误之外,这是一种很好的做法。

C: No continue necessary

C:不需要继续

largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = float(inp)
    except ValueError: #and not all errors!
        print "Invalid input"
    else: 
        # This block will execute if no exception is caught.
        # Yes, this is valid python.
        if smallest is None: #first number!
            smallest = num
            largest = num
        elif num < smallest:
            smallest = num
        elif num > largest:
            largest = num

print "Maximum is", largest
print "Minimum is", smallest

回答by Shoua Iqbal

Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

编写一个程序,反复提示用户输入整数,直到用户输入“完成”。输入“完成”后,打印出最大和最小的数字。如果用户输入的不是有效数字的任何内容,则使用 try/except 捕获它并发出适当的消息并忽略该数字。

largest = None
smallest = None

while True:
    inp = raw_input("Enter a number: ")

    if inp == "done":
        break

    try:
        num = int(inp)

        if smallest is None:
            smallest = num
        elif num < smallest:
            smallest = num
        elif num > largest:
           largest = num
    except:
        print "Invalid input"

    continue

print "Maximum is", largest
print "Minimum is", smallest 

error if mismatch appears after execution

如果执行后出现不匹配则出错

回答by Rohit Joshi

largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = int(inp)
    except:
        print "Invalid input"
        continue
    if smallest is None:
        smallest = num
    elif num < smallest:
        smallest = num
    if largest is None:
        largest = num
    elif num > largest:
        largest = num

print "Maximum is", largest
print "Minimum is", smallest

回答by Nada Sami

largest = None
smallest = None
while True:
    num = raw_input("Enter a number:")
    if num == "done": break
    try: 
       nom = int(num)
    except: 
       print "Invalid input"
       continue

    if largest is None:
        largest = nom
    elif nom >  largest:
        largest = nom

    if smallest is None:
        smallest = nom
    elif nom < smallest:
        smallest = nom


print "Maximum is", largest
print "Minimum is", smallest

回答by Rabins Sharma Lamichhane

You should include your logic in your try: block to run this program logically. It will run even if you put your logic inside the catch block.

您应该在 try: 块中包含您的逻辑以逻辑地运行此程序。即使您将逻辑放在 catch 块中,它也会运行。

Placing the logic (if/else) after the catch is not able to calculate your highest and lowest number for the number you entered before the Error caught.

在捕获之后放置逻辑(if/else)无法计算您在捕获错误之前输入的数字的最高和最低数字。

Correct Method

正确方法

largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == 'done': break
    try:
        ival = int(num)
                # This block will execute if no exception is caught.
        # Yes, this is valid python.
        if smallest is None: #first number!
            smallest = ival
            largest = ival
        elif ival  largest:
            largest = ival

    except ValueError: #and not all errors!
        print ('Invalid input')
        continue 


print('Maximum is', largest)
print('Minimum is', smallest)

Wrong Method

错误的方法

    largest = None
    smallest = None
    while True:
        num = input("Enter a number: ")
        if num == 'done': break
        try:
            ival = int(num)
        except ValueError:
            print ('Invalid input')
            continue 
    if smallest is None:
                smallest = ival
                largest = ival
            elif ival  largest:
                largest = ival

    print('Maximum is', largest)
    print('Minimum is', smallest)

回答by Manish Kumar

Code:

代码:

largest = None
smallest = None

while True:
num = input("Enter a number: ")
if num == "done":
    break
try:
    n = int(num)
    if smallest is None or n < smallest:
        smallest = n
    if largest is None or n > largest:
        largest = n
except ValueError:
    # num cannot be converted to an int
    print ("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)

Output:

输出:

Invalid input
Maximum is 10
Minimum is 2

回答by Vikrant

Try this code ....

试试这个代码....

largest = None
smallest = None

while True:
    num = input("Enter a number: ")
    if num == "done" : 
        break 
    try:
        inp=float(num)
    except:
        print("Invalid input")
        continue

for value in [7,2,10,4]: 
    if largest is None:
        largest = value
    elif value>largest:  
        largest=value
        print("Maximum is", largest)            
for value in [7,2,10,4]: 
    if smallest is None:
        smallest = value
    elif value < smallest:
        smallest=value          
        print("Minimum is", smallest)

回答by jv02

Here is the correct answerenter image description here

这是正确答案在此处输入图片说明

largest = None smallest = None

最大 = 无 最小 = 无

inp_list = [] while True: inp = raw_input("Enter a number: ") if inp == "done": break else: inp_list.append(inp)

inp_list = [] while True: inp = raw_input("Enter a number:") if inp == "done": break else: inp_list.append(inp)

for num in inp_list: try: num = int(num) if smallest is None: smallest = num if num > largest : largest = num elif num < smallest : smallest = num except:
print ('Invalid input')

对于 inp_list 中的 num:尝试:num = int(num) 如果最小的是 None:最小 = num 如果 num > 最大:最大 = num elif num < 最小 = num 除了:
打印('无效输入')

print ("Maximum is", int(largest)) print ("Minimum is", int(smallest))

打印(“最大值”,整数(最大))打印(“最小值”,整数(最小))

回答by user11242194

largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = int(inp)
    except ValueError: #and not all errors!
        print ("Invalid input")
    else: 
        # This block will execute if no exception is caught.
        # Yes, this is valid python.
        if smallest is None: #first number!
            smallest = num
            largest = num
        elif num < smallest:
            smallest = num
        elif num > largest:
            largest = num

print ("Maximum is", largest)
print ("Minimum is", smallest)

回答by Alessander Oliveira

#by Aless
largest  = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done" : break

    try:
        intNum = int(num)
    except ValueError:
        #print('Error: Invalid input', num)
        print('Invalid input')
        continue
    else:
        if (largest  < intNum): largest = intNum
        if (smallest > intNum) or (smallest is None): smallest = intNum

print("Maximum", largest)
print("Minimum", smallest)