0

This is some code I wrote for school. The problem is that it gets extremely long in two areas if I keep adding more "input" functions, the lines used and the number of "and" functions I use. It's so big, that it's making my school assignment page lag. If you wanted to do it with 7 numbers or more, then it would make my page lag even more. How do I simplify the code below?

Assignment: Write a program to input 6 numbers. After each number is inputted, print the biggest of the numbers entered so far.

num1 = int(input("Enter a number:"))
print ("Largest: " + str(num1) + "\n")

num2 = int(input("Enter a number:"))
if (num1 > num2):
    print ("Largest: " + str(num1) + "\n")
else:
    print ("Largest: " + str(num2) + "\n")

num3 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3):
    print ("Largest: " + str(num1) + "\n")
elif (num2 > num3):
    print ("Largest: " + str(num2) + "\n")
else:
    print ("Largest: " + str(num3) + "\n")

num4 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4):
    print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4):
    print ("Largest: " + str(num2) + "\n")
elif (num3 > num4):
    print ("Largest: " + str(num3) + "\n")
else:
    print ("Largest: " + str(num4) + "\n")

num5 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4 and num1 > num5):
    print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4 and num2 > num5):
    print ("Largest: " + str(num2) + "\n")
elif (num3 > num4 and num3 > num5):
    print ("Largest: " + str(num3) + "\n")
elif (num4 > num5):
    print ("Largest: " + str(num4) + "\n")
else:
    print ("Largest: " + str(num5) + "\n")

num6 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4 and num1 > num5 and num1 > num6):
    print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4 and num2 > num5 and num2 > num6):
    print ("Largest: " + str(num2) + "\n")
elif (num3 > num4 and num3 > num5 and num3 > num6):
    print ("Largest: " + str(num3) + "\n")
elif (num4 > num5 and num4 > num6):
    print ("Largest: " + str(num4) + "\n")
elif (num5 > num6):
    print ("Largest: " + str(num5) + "\n")
else:
    print ("Largest: " + str(num6) + "\n")
LukeyBear
  • 88
  • 5
  • 2
    Have you learned yet about loops? – Daniel Pryden Oct 30 '18 at 19:15
  • 4
    @Carcigenicate: Or just use `max`. – ShadowRanger Oct 30 '18 at 19:16
  • Along with loops, are you allowed to use any of the built-in functions or data structures, or is this intended to be a "implement everything from scratch" exercise? A loop that `input`s, `append`s to an ever-growing `list`, and uses `max` to extract the current largest value each time would be the obvious solution. – ShadowRanger Oct 30 '18 at 19:17
  • I haven't really learned about for loops, and not while loops or list s yet. This is pretty much my first year of programming. We kind of learned about max, but I haven't used it much. – LukeyBear Oct 30 '18 at 19:18
  • @LukeyBear: What about `while` loops? `list`s? – ShadowRanger Oct 30 '18 at 19:18
  • 2
    Storing in a `list`, whether sorting or using `max`, is overkill. On each iteration there is only one new number to consider, and only two cases: either it is now the largest (in which case the previous largest value is no longer needed) or the previously largest value is still largest, in which case the new number does not need to be stored at all (the previous largest is still the largest). – Daniel Pryden Oct 30 '18 at 19:19
  • @DanielPryden: True. There are some small advantages on straightforward code to using a `list` and `max` (you can do a lot of things that appear branchless, even if there are tons of branches under the hood, where the non-`list` approach isn't necessarily as easy/obvious to express succinctly), and for a new coder, I can see where holding onto the complete set of values is convenient. If they can't use loops/`list`s though, the only way to simplify is your approach, so they're not writing progressively more complex `if`/`elif` checks for each new number. – ShadowRanger Oct 30 '18 at 19:22

2 Answers2

1

This can be done without any lists or special syntax as long as you use a simple loop to run the body six times:

largest = None
for _ in range(6):
    number = int(input('Enter a number: '))
    if largest is None or number > largest:
        largest = number
    print('Largest: {}\n'.format(largest))

If for some reason you're not allowed to use a loop, you can get the same result by manually unrolling the loop:

largest = int(input('Enter a number: '))
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
0

You can just store the number in a variable and overwrite it when your user enters a larger one.

awesome_number = 0
while True: # Always loop unless we break the loop.
    userInput = int(input("Enter a number:")) # Your input phrase

    # Compare values, evaluates to True if the user input is greater
    if userInput > awesome_number: 
        awesome_number = userInput # Overwrite if compare evaluates to True
    # Print using the .format method to dynamically insert the greatest
    # number
    print("So far, the biggest number you've entered is {}".format(awesome_number))

If you want to stop after n number of inputs, you could add a simple counter to count iterations.

awesome_number = 0
counter = 0
while True: # Always loop unless we break the loop.
    userInput = int(input("Enter a number:")) # Your input phrase

    # Compare values, evaluates to True if the user input is greater
    if userInput > awesome_number: 
        awesome_number = userInput # Overwrite if compare evaluates to True
    # Print using the .format method to dynamically insert the greatest
    # number
    print("So far, the biggest number you've entered is {}".format(awesome_number))
    # Increment the counter
    counter = counter + 1
    if counter == 500: # Arbitrary number to end on
        break
Charles Landau
  • 4,187
  • 1
  • 8
  • 24
  • 1
    The OP does want to stop eventually, so an infinite loop is probably not the way to go. If they're not allowed to use `for` loops (because their teacher likes teaching bad habits I guess?), a `while` that simulates one would be a reasonable alternative. – ShadowRanger Oct 30 '18 at 19:24
  • Zero isn't a great value to use as a sentinel -- what if the user only enters negative numbers? – Daniel Pryden Oct 30 '18 at 19:27
  • This works on https://www.onlinegdb.com/, but not on http://www.codeskulptor.org/, the website I usually use to code. (although I use OnlineGDB if CodeSkulptor doesn't work) On CodeSkulptor, I get the error Line 6: AttributeError: 'str' object has no attribute 'format'. Also, I'm not sure if it will work on my school quiz and get a good grade. (because it's still laggy and I can't test it) Good answer though! – LukeyBear Oct 30 '18 at 19:28
  • The attribute error can but fixed by doing `print("So far, the biggest number you've entered is " + awesome_number)`, their python just doesn't support `.format` – Charles Landau Oct 30 '18 at 19:29
  • 2
    @LukeyBear: What version of Python are you using? [`str.format` has existed since 2.6](https://docs.python.org/2/library/stdtypes.html#str.format), and that's well over a decade old at this point. If it's just where you're developing, I'd suggest actually installing a local interpreter; if your school mandates submission on some ancient platform though, we'd need to know. – ShadowRanger Oct 30 '18 at 19:30
  • @DanielPryden good point, but lukey mentioned being a beginner and I opted for simplicity over covering all the cases. – Charles Landau Oct 30 '18 at 19:31
  • Good fix, but you still gave me errors. I got Line 10: TypeError: cannot concatenate 'str' and 'int' objects. I managed to fix that though. :) – LukeyBear Oct 30 '18 at 19:34
  • Yea you just need to enclose it in `str()`, my fault. @LukeyBear I just want to point out that the version of python you are using is so very old. Python 2.7 will be deprecated in just over a year – Charles Landau Oct 30 '18 at 19:36
  • @ShadowRanger I edited the post to include an end condition per your comment – Charles Landau Oct 30 '18 at 19:39
  • My school indeed wants me to code on the old version because Edhesive didn't update their strategy on my course for "years" (Python 2.something) I heard CodeSkulptor removed various functions from Python, although there is a CodeSkulptor that uses Python 3. However, I think this question is also kind of valid for Python 3.x. – LukeyBear Oct 30 '18 at 19:40
  • @LukeyBear That's awful. Use this http://python-future.org/compatible_idioms.html and try not to learn any bad habits. Read PEP-8 – Charles Landau Oct 30 '18 at 19:45