Smallest/largest numbers program, input must stop once negative number is inserted - python

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

Related

Happy Numbers doesn't update variable

I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))

Writing a pseudocode algorithm for GCSE

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.

how to calculate an average after a while loop

I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
"Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1."
The while loop i can do... The calculation is what im stuck on.
negative = "-1"
passable = "0"
while not passable <= negative:
passable = input("Write a number: ")
I just want to get this to work and a explanation if possible
As pointed out by some of the other answers here, you have to sum up all your answers and divide it by how many numbers you have entered.
However, remember that an input() will be a string. Meaning that our while loop has to break when it finds the string '-1' , and you have to add the float() of the number to be able to add the numbers together.
numbers=[]
while True:
ans=input("Number: ")
if ans=="-1":
break
else:
numbers.append(float(ans))
print(sum(numbers)/len(numbers))
I would initialize a list before asking the user for a number, using a do-while. Then, you add every number to that list unless the number == -1. If it does, then you sum every element in the list and output the average.
Here's pseudocode to help:
my_list = []
do
input_nb = input("Please enter a number: ")
if(input_nb != -1)
my_list.add(input_nb)
while (input_nb != -1)
average = sum(my_list) / len(my_list)
print('My average is ' + average)
You are assigning strings to your variables, which I don't think is your intention.
This will work:
next_input = 0
inputs = []
while True:
next_input = int(input('Please enter a number:'))
if next_input == -1:
break
else:
inputs.append(next_input)
return sum(inputs) / len(inputs)
First, you need to create a container to store all the entered values in. That's inputs, a list.
Next, you do need a while loop. This is another way of structuring it: a loop that will run indefinitely and a check within it that compares the current input to -1, and terminates the loop with break if it does. Otherwise, it appends that input to the list of already entered inputs.
After exiting the loop, the average is calculated by taking the sum of all the values in the entered inputs divided by the length of the list containing them (i.e. the number of elements in it).

python:Write a program that keeps reading positive numbers from the user [duplicate]

This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)

Finding numbers that are multiples of and divisors of 2 user inputted numbers

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

Categories