Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
Python3- Having difficulty getting the smallest number with a for-loop.
Task = Write a program that asks the user for ten numbers, and then prints the largest, the smallest, and how many are dividable by 3. Use the algorithm described earlier in this chapter. CODE: largest = 0 smallest = 0 amount=0 for count in range (1,11): num= int(input("please enter a number")) if num % 3 == 0: amount = amount + 1 if num > largest: largest = num if (number < smallest): smallest = number; print ("you have",amount,"numbers divisible by three" ) print( "Smallest is", smallest ) print( "Largest is", largest ) Could anyone please help me to get the number to be the actual smallest number inputted rather than 0? Thank you!
5 Answers
+ 2
I think.. as you've initialise the smallest to 0, unless someone enters a negative number then the smallest will always be 0...so i initialise it to something else, even if it's 10000...it depends on the range of ints you expect someone to input.
+ 1
Try
if num < smallest:
instead of
if number < smallest
😉
+ 1
@Thomas..ahhhh yesssss..that would be better....
declare a "flag"...set it to False...(along side your other variables).
In the loop, just after your input, test the flag and set the largest and smallest to num (or not.... as appropriate).
and at the end of your "if statements..change the flag to "True".
+ 1
Thank you so much everyone! it worked now!!
0
That's a good point.
Maybe you can set the allmost first input to this "smallest"
Then, it would be only changed, if one of the following inputs is smaller.