python loops and arrays - python

Question: Create a program that allows the user to enter 10 different integers. If the user tries to enter
an integer that has already been entered, the program will alert the user immediately and
prompt the user to enter another integer. When 10 different integers have been entered,
the average of these 10 integers is displayed.
This is my code:
mylist = []
number = int(input("Enter value: "))
mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
if number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
else:
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
This kind of works but I need to create a loop that will keep on asking the user for another number if the number is in the array. Can you help?

What about:
mylist = []
number = int(input("Enter value: ")) mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
while number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
print(sum(mylist)/float(len(mylist)))

Related

I'm getting an error trying to find the max an min of a set of inputs by the user

This is my assigned task :
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and having as output:
Invalid input
Maximum is 10
Minimum is 2
This is what I have so far but is not showing me the maximum neither the minimum of the inputs , as is not showing the Invalid input whenever the user try to put any word in it .
list = []
for i in range(2,10):
list.append(int(input('Ingrese un nĂºmero\n')))
# Ordenar lista
list.sort()
# Numero menor
print(list[0])
# Numero mayor
print(list[-1])
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
Code:-
lis = []
while True:
try:
num=int(input("Enter a number: "))
lis.append(num)
except ValueError:
print("It is not a number.. please verify!! Invalid input\n")
check=input("If you want to continue to write number please enter. if you are done please write done:\n")
if check.lower() == "done":
break
print("Maximum", max(lis))
print("Minimum",min(lis))
Output:-
Enter a number: 7
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 2
If you want to continue to write number please enter. if you are done please write done:
Enter a number: bob
It is not a number.. please verify!! Invalid input
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 10
If you want to continue to write number please enter. if you are done please write done:
done
Maximum 10
Minimum 2
You can use walrus operator (:=) to prompt and check if num equals 'done' or not. Catch invalid num using try except and add num to numlist if it can be casted to int. Print out the largest and the smallest num of numlist using max() and min().
numlist = []
while (num := input('Enter a number: ')) != 'done':
try: numlist += [int(num)]
except ValueError: print('Invalid input')
print('Maximum is', max(numlist))
print('Minimum is', min(numlist))
Output:
Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Maximum is 10
Minimum is 2

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

My while loop should be running until the user wants to stop it but ends after the 2nd input

I feel like the question is not well worded for a question, but this is what I really want:
I am writing this code where a 'user' can enter as many integers from 1 to 10 as he/she wants. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one. Calculate and display the average of the integers in the list.
Isn't 'while' supposed to running part of a program over and over and over again until it stops when it is told not to?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
It stops after the 2nd time even if the user types in 'y'. It then gives me the 'Number List: ".
Once again, you guys have been great assisting my classmates and I. Im in an introduction to Python course and we are learning about loops and lists.
One while loop is sufficient to achieve what you want.
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
The while loop runs as long as again == 'y'. The program asks for another number if the user inputs an integer not between 1 and 10.
Try this:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
I'm not sure why you had two different while loops, let alone three. However, this should do what you want. It will prompt the user for a number, and try and convert it to a float. If it can't be converted, it will prompt the user again. If it is converted it will check to see if it's between 0 and 10 and if it is, it will add it to the list, otherwise, it will tell the user that that's an invalid number.

I am trying to get my program to take only integers and stop when the user presses 0

So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")

'int' object is not iterable in python 3

got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)

Categories