1

Write a program that prompts the user for a number from 1 to 20 until the number 20 is encountered. Not including the 20, calculate the maximum value.

Can someone help me to write a code ?

inp = 0
x = 9999
while inp != 20:
    inp = int(input("Please enter a number from 1 to 20 (20 to stop): "))
    print(inp)
    if inp != 20:          

print("the maximum value is", inp)

I am stuck

0

3 Answers 3

1

You're on the right track, but you need a separate variable to hold the largest number -- you can't reuse the input variable for that purpose.

Also, since you're already checking if the input is 20 inside the loop, it's repetitive to also check the same thing in the while condition. Just use while True.

# keep track of the largest number entered
largest = 0

# loop forever
while True:
    # ask for input
    inp = int(input("Please enter a number from 1 to 20 (20 to stop): "))

    # if 20 was entered, quit the loop
    if inp == 20:
        break

    # if the input is larger than the largest number entered so far, save it as the largest
    if inp > largest:
        largest = inp

print("The largest number was", largest)
Sign up to request clarification or add additional context in comments.

Comments

0

a rather simple solution

prompt = "Please enter a number from 1 to 20 (20 to stop): "

# stores the numbers that were inputted
numbers = []

number = int(input(prompt))

# keeps asking for input as long as number inputted, is not 20
while number != 20:
    numbers.append(number)
    number = int(input(prompt))

# gets the max value from the list, and prints it
print("the maximum value is", max(numbers))

Comments

0

Having a sentinel is a good use case for iter:

max(iter(lambda: int(input("Please enter a number from 1 to 20 (20 to stop): ")), 20))

Demo:

>>> max(iter(lambda: int(input("Please enter a number from 1 to 20 (20 to stop): ")), 20))
Please enter a number from 1 to 20 (20 to stop): 4
Please enter a number from 1 to 20 (20 to stop): 12
Please enter a number from 1 to 20 (20 to stop): 7
Please enter a number from 1 to 20 (20 to stop): 20
12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.