Python循环中如何在偶数输出句末添加"and"以格式化语句?
Hey there! I see you're working on a Python script to collect numbers, find the maximum, and list even numbers—great start! Let's fix that output formatting so your even numbers line ends with "and" for the last element, just like you want.
First, Let's Understand the Current Issue
Your current code uses ", ".join(par) to list even numbers, which works for basic comma separation but doesn't handle the "and" for the final item. Also, since par is a set, it's unordered—you already used sorted(par) to fix that, but let's integrate that into our formatting logic properly.
Step-by-Step Fix
Here's how to adjust your code to get the exact output you want:
Store even numbers as integers (optional but cleaner)
Instead of adding strings to yourparset, store integers first—this makes sorting more reliable (though it works with strings too, integers are better practice). Change this line:par.add(str(i))to:
par.add(i)Format the even numbers with proper "and" placement
Replace your final print statement with logic that handles different cases (no even numbers, one even number, multiple even numbers):# Convert sorted even integers to strings for easy formatting even_list = [str(num) for num in sorted(par)] if not even_list: print("Even numbers are none.") elif len(even_list) == 1: print(f"Even numbers are {even_list[0]}.") else: # Join all elements except the last with commas, then add "and" for the final one first_elements = ", ".join(even_list[:-1]) last_element = even_list[-1] print(f"Even numbers are {first_elements}, and {last_element}.")
Full Modified Code
Here's your complete script with the fixes applied:
#! python3 lista = [] par = set() num = int(input("Type a number: ")) while num >= 0: lista.append(num) num = int(input("Type a number: ")) print() print(lista) print("The largest number you introduced is {}".format(max(lista))) print() for i in lista: if i % 2 == 0: par.add(i) # Store integers instead of strings # Format even numbers correctly even_list = [str(num) for num in sorted(par)] if not even_list: print("Even numbers are none.") elif len(even_list) == 1: print(f"Even numbers are {even_list[0]}.") else: first_elements = ", ".join(even_list[:-1]) last_element = even_list[-1] print(f"Even numbers are {first_elements}, and {last_element}.")
How It Works
- No even numbers: Prints a message saying there are none.
- One even number: Shows just that single number without extra punctuation.
- Multiple even numbers: Joins all but the last number with commas, then adds ", and" before the final number to match your desired format (e.g., "2, 4, 8, and 10").
内容的提问来源于stack exchange,提问作者Noelia Sancho Mendez

