Python program for finding greatest of 3 numbers

Published on Aug. 22, 2023, 12:16 p.m.

Here’s an example Python program to find the greatest of three numbers:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a > b and a > c:
    print(a, "is the greatest number")
elif b > a and b > c:
    print(b, "is the greatest number")
else:
    print(c, "is the greatest number")

In this program, we prompt the user to enter three numbers, and convert the input to integers using the int() function. Then we use a series of if and elif statements to compare the three numbers and find the greatest one. We print the result to the console using the print() function.

We compare each number to the other two using the > operator, and use the and operator to ensure that the number is greater than both of them.

You can modify this program to find the greatest of more than three numbers by using a for loop to iterate through the list of numbers and keep track of the greatest one using a variable.

in Python that uses a list and the sort() method to sort a list of numbers in ascending order

Sure! Here’s an example program in Python that uses a list and the sort() method to sort a list of numbers in ascending order:

numbers = [5, 2, 8, 1, 9, 3]
numbers.sort()
print(numbers)

In this program, we define a list of numbers and call the sort() method on the list. This method sorts the list in ascending order. We then print the sorted list to the console using the print() function.

If you want to sort a list in descending order, you can pass the reverse=True argument to the sort() method:

numbers = [5, 2, 8, 1, 9, 3]
numbers.sort(reverse=True)
print(numbers)

This will sort the list in descending order.

You can also use the sorted() function to sort a list. The sorted() function returns a new sorted list, and leaves the original list unchanged:

numbers = [5, 2, 8, 1, 9, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

This will also sort the list in ascending order.

Note that you can use the key parameter to sort the list based on a specific condition or function. For example, you can sort a list of strings based on their lengths as follows:

words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)
print(words)

This will print ["date", "apple", "banana", "cherry"], since “date” has the shortest length, followed by “apple”, “banana”, and “cherry”, respectively.

Tags:

related content