the program asks user to enter 5 unique number, if the number is already in the list, ask for a new number. after 5 unique numbers have been entered, display the list
numbers = ['1','2','3','4','5']
count = 0
index = 0
while count <6:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
if user not in numbers:
print "unique"
count += 1
numbers = numbers.replace(index,user)
index +=1
print numbers
when the program gets to the replace method, it raise an attribute error
You can use:
numbers[index] = user
A list doesn't have a replace() method. A string does have a replace method however.
If you wish to append a number to the end of a list, you can use append():
numbers.append(user)
If you wish to insert a number at a given position, you can use insert() (for example, position 0):
numbers.insert(0, user)
You don't have to initialize a list in Python:
numbers = []
while len(numbers) != 5:
num = raw_input('Enter a number: ')
if num not in numbers:
numbers.append(num)
else:
print('{} is already added'.format(num))
print(numbers)
You can replace it with Subscript notation, like this
numbers[index] = user
Apart from that your program can be improved, like this
numbers = []
while len(numbers) < 5:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
else:
print "unique"
numbers.append(user)
print numbers
If you don't care about the order of the numbers, you should probably look into sets. Addidionally, if you want to work with numbers, not strings, you should cast the string to an int. I would've written something like this.
nums = set()
while len(nums) < 5:
try:
nums.add(int(raw_input("Enter a number: ")))
except ValueError:
print 'That is not a number!'
print 'Numbers entered: {}'.format(', '.join(str(x) for x in nums))
Output:
Enter a number: 5
Numbers entered: 5
Enter a number: 3
Numbers entered: 3, 5
Enter a number: 1
Numbers entered: 1, 3, 5
Enter a number: 7
Numbers entered: 1, 3, 5, 7
Enter a number: 9
Numbers entered: 1, 3, 9, 5, 7
Related
I've been working on a small program to learn more about Python, but I'm stuck on something.
Basically, the user has to input a sequence of positive integers. When a negative number is entered, the program stops and tells the user the two largest integers the user previously inputted. Here is my code:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while (number > 0):
number = int(input())
if number < 0:
break
largestInteger = max(numbers)
print(largestInteger)
integers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
There are two issues with your code:
You need to update the list with the user input for every iteration of the while loop using .append().
integers isn't defined, so you can't call .remove() on it. You should refer to numbers instead.
Here is a code snippet that resolves these issues:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while number > 0:
number = int(input())
if number > 0:
numbers.append(number)
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
I would build a function that would call itself again if the user enters a number larger or equal to 0, but will break itself and return a list once a user inputs a number smaller than 0. Additionally I would then sort in reverse (largest to smallest) and call only the first 2 items in the list
def user_input():
user_int = int(input('Please enter your desired integers'))
if user_int >= 0:
user_lst.append(user_int)
user_input()
else:
return user_lst
#Create an empty list
user_lst = []
user_input()
user_lst.sort(reverse=True)
user_lst[0:2]
You forgot to append the input number to the numbers list
numbers = []
while (True):
number = int(input())
if number < 0:
break
numbers.append(number)
print("First largest integer: ", end="")
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
print("Second largest integer: ", end="")
largestInteger2 = max(numbers)
print(largestInteger2)```
The above code will work, according to your **desire**
The assignment
So heres the problem, i have a to write a program thats takes input from user until he writes "done".
When that happens, i should take the biggest and smallest value and print them out.
The problem
When i write "done" it tells me that i cant compare an str to a int, and also, it doesnt store every value i wrote in my input() function.
The code
while True:
number = input("Enter number:")
if number == "done":
break
largest = None
for value in number:
if value > largest or largest is None:
largest = value
print("after:", largest)
smallest = None
for value in number:
if value < smallest or smallest is None:
smallest = value
print("after",smallest)
you overwrite number at each loop cycle. Use a container to hold the numbers:
numbers = []
while True:
number = input("Enter number:")
if number == "done":
break
else:
numbers.append(int(number))
print(numbers)
output:
Enter number:1
Enter number:2
Enter number:3
Enter number:done
[1, 2, 3]
NB. I also assume you want to use integers, so I provided the conversion (this will fail if you enter anything else than an integers). Also, as your task is simple (min/max) and doesn't need to know the further numbers in advance, I would recommend to compute those min/max in the while loop. This will be more efficient than reading again 2 times the list (see below).
numbers = [] # not needed if you don't want the list as output
smallest = float('inf')
largest = float('-inf')
while True:
number = input("Enter number:")
if number == "done":
break
else:
number = int(number)
numbers.append(number) # not needed if you don't want the list as output
if number > largest:
largest = number
if number < smallest:
smallest = number
print(numbers, smallest, largest)
output:
Enter number:1
Enter number:3
Enter number:2
Enter number:done
[1, 3, 2] 1 3
I would suggest using min/max, like this:
numbers = []
while True:
ans = input("give me a number: ")
if not ans or ans == "done":
break
try:
ans = int(ans) # we dont want to add this if it's not really a number
numbers.append(ans)
except:
print("please give me an integer!")
print(numbers,min(numbers),max(numbers))
How I can get number from user that only includes 5 and 6?
I try for loop but it's not work,also try convert the input to string,also no work.how to do?
Number = int(input('enter num')
for x in number:
if 4<x<7:
print('ok)
else:
print ('no')
In python 3, input returns a string. You can easily filter the numbers you want with
val = int(''.join(c for c in input('enter num: ') if c in '56'))
Not sure, why do you need a loop there and why you use x. Try this:
number = int(input('enter num')
if number in [5, 6]:
print('ok)
else:
print ('no')
While I'm sure the others might work, this is yet another way to check for a specific number.
#Gets the number from the user
Number = int(input("Enter Num"))
#checks to see if the number is either 5 or 6
if (Number == 5 or Number == 6):
print("ok") #if it is, it prints ok
else:
print("No") #if it isn't, it prints no
It is probably easier if you check for digits 5 and 6 before converting to int.
Number_str = input('enter num')
for x in Number_str:
if not ord('4')<ord(x)<ord('7'):
print ('no')
break
else:
Number = int(Number_str)
print('ok')
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)))
Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.