Creating an error message for an invalid input in python - python

I have been trying to create a program that creates a list from user input. The program is meant to give an error message to the user input when the length of the list is more or less than nine (9)
For example:
"Please enter nine (9) numbers from 0 - 100: "
input
4 5 6 7 8 9
output
Sorry! Numbers should be up to nine.
or
input
5 67 8 2 90 65 3 45 2 7 1 0
"Sorry! Numbers should not be more than nine."
my code:
number = []
while True:
num = input("Please type numbers: ")
num = list(map(int, num.split()))
number.append(num)
if len(number) > 9:
print ("Numbers should not be more than 9!")
else:
break
print (number)
I don't know what I am doing wrong.
number = []
num = input("Please type numbers: ")
num = list(map(int, num.split()))
number.append(num)
while True:
if (len(number)) == 7:
print ("List is complete")
elif (len(number)) < 7:
print ("List is not complete")
else:
print ("List is more than 7")
break
this code works fine when I'm not asking for user input.
However it brings back the output
"List is not complete" whenever I run it without regard for the length of the string.

Your code creates a list within a list, like this
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]]
to solve this problem, you just have to replace number.append(num) by number = num or simply use directly the variable num like this
num = input("Please type numbers: ")
num = list(map(int, num.split()))
while True:
if (len(num)) == 7:
print ("List is complete")
elif (len(num)) < 7:
print ("List is not complete")
else:
print ("List is more than 7")
break

Related

Print true if the integer has a duplicate, otherwise false

I want to write a program that asks for the list length and its integer elements. From the integer list though, the program needs to find out of there is a duplicate integer and if there is one: print "True" if a duplicate is found, other wise false.
This should be the sample output:
Enter list length: 3
Enter element 1: 100
Enter element 2: 2312
Enter element 3: 12312312
Has duplicate?: False
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
(this part ^ is just for the asking inputs)
for i in range(e):
if e.count(item) > 1:
print("Has duplicate?: True")
else:
print("Has duplicate?: False")
I keep getting an error though:
AttributeError Traceback (most recent call last) <ipython-input-7-d4356802d6f7> in <module> 8 9 for i in range(e): ---> 10 if e.count(item) > 1: 11 print("Has duplicate? True") 12 else: AttributeError: 'int' object has no attribute 'count' –
when you apply count function it should be like list_name.count(the_value_to_count)
but when you are doing e.count(item) e is basically a number not a list,set,tuple..
you can apply count function like this.
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
emp.append(e)
for i in set(emp):
#emp is a list. and i is the number. for which we have to count.
if emp.count(i) > 1:
print(str(i)+" Has duplicate?: True")
else:
print(str(i)+" Has duplicate?: False")
Output:
Enter the number of elements: 6
Enter element 1: 99
Enter element 2: 42
Enter element 3: 63
Enter element 4: 42
Enter element 5: 56
Enter element 6: 99
56 Has duplicate?: False
42 Has duplicate?: True
99 Has duplicate?: True
63 Has duplicate?: False
Note the list is not in order as i have applied set in for loop
Updated answer.
If you just wanted to check if list contains duplicate or not.
Using counter
from collections import Counter
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
emp.append(e)
a=Counter(emp)
if max(a.values()) > 1:
print(" List Has duplicate?: True")
else:
print(" List Has duplicate?: False")
Output:
Enter the number of elements: 5
Enter element 1: 2
Enter element 2: 3
Enter element 3: 1
Enter element 4: 2
Enter element 5: 5
List Has duplicate?: True

How do I multiply output by user input in Python?

I'm looking for a user to give a number, and my output be stars/astericks as many times as they entered.
Here is my code. My aim was to receive a number of inputs from user, then give them back their input. All of this works 90% as intended.
listSize = input("Hello, please enter an integer "
"value the size of your list: ")
l = list()
for i in range(int(listSize)):
oneToTen = int(input("Please enter an integer "
"value between 1 and 10 (inclusive): "))
if oneToTen <= 0:
oneToTen = 1
elif oneToTen > 10:
oneToTen = 10
else:
oneToTen = oneToTen
l.append(oneToTen)
for i in range(0, len(l)):
print (l[i])
For the last 10% I intend for the user to give a star rating to a movie. So instead of the output being their numerical inputs, I want the output to be a number of asterisks based on their input. This part works, but I don't know how to combine my two sets of code.
star = "*"
stars = oneToTen * star
print(stars)
Example: If a user inputs 4, currently the output is "4". Instead, I would like the output to be "****"
Thank you!
Simply replace the last print message with the star code.
listSize = input("Hello, please enter an integer "
"value the size of your list: ")
l = list()
for i in range(int(listSize)):
oneToTen = int(input("Please enter an integer "
"value between 1 and 10 (inclusive): "))
if oneToTen <= 0:
oneToTen = 1
elif oneToTen > 10:
oneToTen = 10
else:
oneToTen = oneToTen
l.append(oneToTen)
star = "*"
for i in range(0, len(l)):
stars = l[i] * star
print(stars)
You were almost there:
listSize = input("Hello, please enter an integer "
"value the size of your list: ")
data = list()
for i in range(int(listSize)):
oneToTen = int(input("Please enter an integer "
"value between 1 and 10 (inclusive): "))
if oneToTen <= 0:
oneToTen = 1
elif oneToTen > 10:
oneToTen = 10
data.append(oneToTen)
for i in data:
star = "*"
stars = i * star
print(stars)
It's good that you are thinking about checking what the user enters. Never trust user input. What happens if the user doesn't enter a number?
Please enter an integer value between 1 and 10 (inclusive): hello world
this will give a ValueError. You can handle that like this:
try:
starCount = int(input("Hello, please enter an integer, from 1 to 10: "))
except ValueError:
print("You didn't enter a number")
exit(1)
This way we will only get past that point if the input is an integer. That means it's safe to do some math with the inputted value, and there is a quick way to restrict the range of an integer in this case:
starCount = starCount % 11
This will take the remainder of the input value divided by 11, which will always be between 0 and 10, inclusive.
Python will let you multiply a string by an integer, so this is valid:
print("*" * starCount)
Finally, it can all be put together into a function:
def f():
try:
starCount = int(input("Hello, please enter an integer, from 1 to 10: "))
starCount = starCount % 11
print("*" * starCount)
except ValueError:
print("You didn't enter a number")
>>> f()
Hello, please enter an integer, from 1 to 10: 10
**********
>>> f()
Hello, please enter an integer, from 1 to 10: a
You didn't enter a number

can a condition be in range in python?

can a range have a condition in python? for example, I wanna start at position 0 but I want it to run until my while statement is fulfilled.
total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num
I want to be able to save different variables being in a while loop.
The purpose of my program is to print the sum of the numbers you enter unil you put in 0
my code
num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
number_enterd = num
print( "Total is =", total )
print(number_enterd) #check to see the numbers ive collected
expected output:
enter an integer number (0 to end): 10
1+2+3+4+5+6+7+8+9+10 = 55
as of right now I'm trying to figure out how to store different variables so i can print them before the total is displayed. but since it is in a loop, the variable just keeps getting overwritten until the end.
If you want to store all the numbers you get as input, the simplest way to do that in Python is to just use a list. Here's that concept given your code, with slight modification:
num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number
while num != 0:
total += num
numbers_entered.append(num)
num = int(input ( "Enter a number: " ))
print("Total is = " + str(total))
print(numbers_entered) #check to see the numbers ive collected
To get any desired formatting of those numbers, just modify that last print statement with a string concatenation similar to the one on the line above it.
I used a boolean to exit out of the loop
def add_now():
a = 0
exit_now = False
while exit_now is False:
user_input = int(input('Enter a number: '))
print("{} + {} = {} ".format(user_input, a, user_input + a))
a += user_input
if user_input == 0:
exit_now = True
print(a)
add_now()
If you want to store all of the values entered and then print them, you may use a list. You code would end like this:
#number_enterd = str() # This is totally unnecessary. This does nothing
num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
#number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
# It doesn't even make the num a string
numsEntered.append(num) #This adds the new num the user just entered into the list
print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request.
Your output will be:
>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]
Just as a guide, this is how I would do it. Hope it helps:
num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
numsEntered.append(num) #This adds the num the user just entered into the list
total += num
num = int(raw_input("Enter a number: "))
print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum.
Hope you like my answer! Have a good day :)

Separating an inputted integer into a list to check if each element of the list meets the requirements

input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
for n in number:
a = int(n)
if len(number)!=5 or number>5 or number<0 :
print ('invalid input')
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
My program is checking the 5 digits which are inputted as if they are one number but I want my program to first make sure that 5 digits are inputed and then check if they are between 0 and 5 but the program combines all 5 digits into one number, I want the program to check each element of the list on it's own and before printing anything I want the program to check if the inputted number meets all the conditions and if does not to print (Invalid Input) and stop their
input_list = input("Enter numbers separated by spaces: ")
numbers = input_list.split()
if len(numbers) == 5 and all(0 <= int(n) <= 5 for n in numbers):
print("ok")
print("".join(numbers))
else:
print("invalid")
I use raw_input in python 2. input is fine for python 3.
input_list = raw_input("Enter numbers separated by spaces: ").split()
numbers = [int(n) for n in input_list if 0 <= int(n) <= 5]
if len(numbers) != 5:
print ('invalid input')
for a in numbers:
if a == 0:
print ('.')
else:
print ('x'* a)
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
else:
print ("Number does not lie in the range 0 to 5.")
else:
print ("Invalid Input.")
Yes, the above works but is should check input first to make sure it is valid
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'

Checking if input meets the requirements before printing anything

input_list = raw_input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print 'x'* a
elif a == 0:
print '.'
else:
print "Number does not lie in the range 0 to 5."
else:
print "Invalid Input."
I want my program to check if the 5 inputted numbers meets all the conditions and if even one them fails to print INVALID INPUT and stop the program. Also I don't quite understand how my program checks each inputted number on its own as my teacher helped me but didn't explain it .
The program should ask for the number five times before printing anything
The program must check that the input are numbers are between 0 and 5. It will also fail if a number of digits is entered other than 5. Failed input can terminate the program with an appropriate error message.
Inputted numbers may be duplicates. (ex. 3, 3, 3, 0, 0 is acceptable input.)
This is what Python's assert statement does:
>>> x = 5
>>> try:
... assert(x==4)
... except(AssertionError):
... print("Error!")
...
>>> Error!
In the assert clause, you are stating a boolean condition which you are forcing to be true. If it is not true, you can catch the error using the except statement and handle it there.
In your case you could have:
assert(((x <= 5) and (x >= 0)))
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'

Categories