Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Function To Check And Return Whether The Points Are Collinear Or Not
Title :
Write A Python Function To Check Whether The List Is Ascending Order Or Not
Description :
Hi guys, in this article you will learn a python program that uses a python function to check if a given list is in ascending order or not.
Define a function check_ascending() and pass a list of numbers as input arguments to it.
Take the previous variable and initialize that as the first item of the list. Now iterate all the numbers from list and consider as next.
Compare previous and next values. If the previous is greater than the next return false, the signifying list is not ascending. Swap previous values to next every iteration.
def check_ascending(items):
previous = items[0]
for next in items:
if previous > next:
return False
previous = next
return True
In the main program take length variable to store number list length, take empty list variable and use for loop to iterate until list length. Keep prompting the user to enter a number and append it to the list.
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
temp = float(input("Enter a Number : "))
numbers.append(temp)
Now using if statement call the function check_ascending() by passing list as input argument. Print list is ascending if function returns true else print list is not ascending.
if check_ascending(numbers):
print("Given List is in Ascending Order")
else:
print("Given List is Not in Ascending Order")
Complete Python Code :
def check_ascending(items):
previous = items[0]
for next in items:
if previous > next:
return False
previous = next
return True
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
temp = float(input("Enter a Number : "))
numbers.append(temp)
if check_ascending(numbers):
print("Given List is in Ascending Order")
else:
print("Given List is Not in Ascending Order")
Output :
Enter List Length : 5
Enter a Number : 1
Enter a Number : 2
Enter a Number : 2
Enter a Number : 2
Enter a Number : 3
Given List is in Ascending Order
Output :
Enter List Length : 5
Enter a Number : 1
Enter a Number : 2
Enter a Number : 3
Enter a Number : 2
Enter a Number : 3
Given List is Not in Ascending Order
Conclusion :
The above Python program uses a Python function to check if the given list of numbers is in ascending order or not.
Take the first index value of the given list as the previous variable and keep iterating the list of numbers and getting the next value out of the list.
Compare the next item with a previous item and return false if the previous item is greater than the next item.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments