Python整数数字比较:如何实现任意位数数字的升序判断
Hey there! Nice work putting together your first Python program for checking ascending digits—let's tweak it so it works with any number of digits, whether that's 1, 7, or even 100 digits long.
The Problem with Your Current Code
Your current code hardcodes comparisons between b[0] vs b[1], b[1] vs b[2], and b[2] vs b[3]. That's why it only works for 4-digit numbers—if someone enters a 7-digit number, you'd miss comparisons between later digits, and if they enter fewer than 4 digits, you'd get an index error.
Solution 1: Use a Loop to Check Adjacent Digits
Instead of hardcoding each pair, we can loop through the digits and compare each digit to the next one. Here's how:
# Get input as a string (no need to convert to int first!) number_input = input("Enter a number: ") # Convert each character to an integer to get our list of digits digits = [int(char) for char in number_input] # Start by assuming the digits are ascending is_ascending = True # Loop through each digit except the last one for i in range(len(digits) - 1): # If current digit is greater than the next one, it's not ascending if digits[i] > digits[i + 1]: is_ascending = False break # No need to check further once we find a violation # Print the result print("Ascending!" if is_ascending else "Not ascending")
Solution 2: Use all() for a More Concise Version
If you want to write this in a shorter, more Pythonic way, you can use the all() function with a generator expression. This checks that every adjacent pair of digits is in non-decreasing order:
number_input = input("Enter a number: ") digits = [int(char) for char in number_input] # Compare each digit to the next one using zip() is_ascending = all(a <= b for a, b in zip(digits, digits[1:])) print("Ascending!" if is_ascending else "Not ascending")
How this works: zip(digits, digits[1:]) pairs each digit with the one right after it (e.g., for [1,2,3,4], it creates pairs (1,2), (2,3), (3,4)). The all() function returns True only if every pair satisfies a <= b.
Bonus: Handle Non-Numeric Input (Optional)
If you want to make your program more robust, you can add a check to make sure the user enters a valid number:
while True: number_input = input("Enter a number: ") if number_input.isdigit(): break print("Please enter a valid number with no spaces or letters!") digits = [int(char) for char in number_input] is_ascending = all(a <= b for a, b in zip(digits, digits[1:])) print("Ascending!" if is_ascending else "Not ascending")
This will keep asking for input until the user enters a valid number.
内容的提问来源于stack exchange,提问作者Alpha Moses

