Sam.Natale - 8 months ago 47

Python Question

Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example:

`Smallest = 0`

count = 0

while count < 10:

Number = int(input("Enter a number >> "))

if Number < Smallest:

Smallest = Number

count = count + 1

print("{0} is the biggest value you have entered".format(Smallest))

But how do I do it in a for loop format? Here's what I have so far:

`for i in range(10):`

Number = int(input("Enter a Number >> "))

if Number < Smallest:

Smallest = Number

print("{0} is the smallest value you have entered.".format(Smallest))

Answer

What you have there, other than the fact you should initialise `Smallest`

, is equivalent to the solution using your `while`

statement.

So, assuming the `while`

variant is considered correct, the `for`

variant you have will suffice.

The reason I qualify it is because initialising `Smallest`

to zero is actually the *wrong* thing to do. If your ten numbers are all greater than twenty (for example), `Smallest`

will remain at zero, giving you the wrong answer.

One way to fix this (in both variants) is to change your `if`

statement to:

```
if i == 0 or Number < Smallest:
```

which will set `Smallest`

first time through the loop regardless (though it should be `count`

in the `while`

variant since that's using a different loop control variable).

Of course, as you learn more and more about the language, you'll come across the concept of things that are more "Pythonic" than others. An example of this is the rather more succinct:

```
Smallest = min(int(input("Enter a Number >> ")) for i in range(10))
```

which removes the need totally for an explicit check-and-replace strategy (that's still done, but under the covers of the `min`

function).

Source (Stackoverflow)