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))
Initialize your Smallest variable and all will works!
Smallest = int(input("Enter a Number >> "))
for i in range(9):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
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).
If you want to get the smallest of the input numbers, you need to start with a minimum a bit bigger than 0... and that is a problem you have with your while loop. It will only work if the user inputs at least one negative number, else it will return 0.
Here is what I suggest:
smallest = float("inf")
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))
Note that I did not capitalize the variables, because to me it makes them look like classes. ^^
Since you are finding the Smallest values out of the input values from the user it is good practice to initially initialize the Smallest variable as maximum possible integer as below.
import sys
Smallest = sys.maxint
Then the rest of your loop will work as properly as it is.
Related
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
My text book asks me to "write pseudo code algorithm which inputs 10 numbers. Each time a number less than zero is input, program displays which number it is, and its value. When all numbers have been input, display the average of all the negative numbers. Your algorithm should allow for the fact that there may be no negative numbers".
The issue I have is that I'm unsure on how to write pseudo code correctly, so I've written it in python code-however, that is not necessarily the task. Furthermore, I've been able to more or less to everything but the issue where I need display the average of all the negative numbers has gotten me stuck... I'm not sure how to add that into my code and I am desperate! Need this for school tomorrow!
count = 0
nums = []
while count != 10:
num = int(input ("enter a number "))
nums.append(num)
if num < 0:
print (num)
neg_nums.append(num)
count = count+1
print (neg_nums)
I actually need to print the average of all the negative numbers, however I have no clue on how I can actually code that into this...
You almost had it. Just store only the negative numbers to the list and then in the end sum all of them up and divide by the amount of negative numbers. I also changed the loop from while loop to for loop, because it makes the code clearer and more compact:
neg_nums = []
for _ in range(10):
num = int(input("enter a number "))
if num < 0:
print(num)
neg_nums.append(num)
if neg_nums:
print(sum(neg_nums) / len(neg_nums))
else:
print("no negative numbers")
We also check in the end if there were some negative numbers inputted, so we don't end up calculating 0 / 0.
Trying to learn Python. Been at this one for hours.
What I am trying to do is to enter a few numbers (for example 7, 4, 6, 10, & 2) and then print the maximum and minimum.
My code works perfectly for every number I enter that is 1-9. Once I hit 10 or higher it goes wonky.
It appears that it is reading 10 as a 1 with a zero attached to it and it says 10 is the minimum.
Where am I going wrong here?
.
The exercise is to enter a few numbers and then print the maximum and minimum. My code works perfectly for every number I enter that is 1-9. Once I hit 10 or higher it goes wonky and lists 10 as the minimum.
Where am I going wrong here?
.
largest = None
smallest = None
the_list = []
while True:
num = input('Enter a number or done: ')
#Handle the edge cases
if num == 'done' : break
if len(num) < 1 : break # Check for empty line
# Do the work
try :
number = int(num)
the_list.append(num)
except:
print("Invalid input")
#continue
print(the_list) # NOTE: This is new so I can see what is in the_list
for value in the_list:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
for the_num in the_list:
if largest is None:
largest = value
elif the_num > largest:
largest = value #the_num
print("Maximum is", largest)
print( "Minimum is", smallest)
The problem is that you are appending the string to the list, not the integer. That is, your list consists of the following right now (if you entered 2 and then 10:
the_list = ['2', '10']
Since strings are compared lexicographically, '10' is less than '2', because '1' is less than '2'. What you want to do is to append the integer.
try :
number = int(num)
the_list.append(number)
except:
print("Invalid input")
#continue
This way, you'll be comparing the numerical values of the numbers, and you'll get the correct answer!
You actually don't append number to the list but you append num to the list (a simple typo, I presume). Thus, you never append an int to the list but the str. Obviously, this will create problems later when you compare strings, such as:
>>> '10' < '3'
True
Change the_list.append(num) to the_list.append(number)
Another error is that in your second for loop you forgot to change value to the_num
I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1
I'm incredibly new to python, so I apologize. I finally got rid of all the syntax errors, but now I just have no idea what I did wrong.
#Get the integers from the user
def main():
largest = 0
smallest = 0
number = int(input('Input a number: '))
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
# This module displays the smallest and largest integer entered.
def showNumber(smallest, largest):
print('The smallest number is: ', smallest)
print('The largest number is: ', largest)
#Call the main
main()
showNumber(smallest, largest)
This is supposed to ask the users for numbers until they put -99, then when they put -99 it's supposed to show the smallest and largest integer.
I know, it's so ugly. I can only use simple data types.
You can add additional 4 characters (spaces) to get it correct, which is by adding indentation on one line
def main():
largest = 0
smallest = 0
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop')) # Indent this line
You can compare your code with the code I show above. There are differences on the line I commented in, which is the amount of preceding space (the indentation)
Because otherwise the while loop will not end, since the number is updated outside the while loop.
Your incorrect code:
while (number != -99):
### The while loop starts here ###
if number > largest:
largest = number
elif number < smallest:
smallest = number
### The while loop ends here ###
number = int(input('Input a number, enter -99 to stop'))
So the while loop will never end, because it keeps comparing the same number, not comparing with the new input. In this case your program does not stop as you said, but rather it is stuck in what is called infinite loop
Python "code block" is defined by the indentation, so codes with the same level of indentation are considered to be in the same code block. So in order to your number to be changing each time you visit the loop, you need to put the input inside the while loop:
The corrected code:
while (number != -99):
### The while loop starts here ###
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
### The while loop ends here ###
Update (by #MERM):
You also have some problem on the showNumber function, as it's not using the variables from the main function. You can call the showNumber function in the main function like MERM has said:
def main():
largest = 0
smallest = 0
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
showNumber(smallest, largest)
And some words of encouragement, your code is not ugly. In fact it's good and concise, precisely solving the problem you're trying to solve. You seem to understand how you should lay out your logic in the code, even though you said you're "incredibly new to python".
Keep it up!
Python is indent sensitive.
The elif and number needs to be at the same indentation as the if. Also, you need to call showNumber from inside main otherwise smallest and largest are undefined (not in the same scope).
def main():
number = int(input('Input a number: '))
largest = number
smallest = number
while (number != -99):
if (number > largest):
largest = number
elif (number < smallest):
smallest = number
number = int(input('Input a number, enter -99 to stop'))
showNumber(smallest, largest)
That should take care of it.