error when validating user input - python

I'm trying to create a menu-driven program that will generate 5 random integers between 0 and 9, and store them in a List. I want it to then allow the user to enter an integer and then search the List, reporting on the location of the integer in the List (if found) or -1 if not. Then display the result of the search to the screen and re-display the menu.
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
import random
def linearSearch(myList):
target = int(input("--->"))
for i in range(len(myList)):
if myList[i] == target:
return i
return -1
#This will generate the five random numbers from 0 to 9
def createList():
newList = []
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
#Option two to display the list
def displayList():
myList = newList
print("Your list is: ", newList)
#Option 3 to search the list
def searchList():
target = int(input("--->"))
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
However when it prompts the user for the five numbers it says invalid no matter what you enter. Could someone please give me an example on how I could fix this?

Careful with your input parsing. Either leave input as a string and deal with strings, or initially cast it to an int and continue dealing with ints.
myChoice = str(input())
# input 1
if myChoice in ['1', '2', '3', '4']:
print(myChoice)
or
myChoice = int(input())
# input 1
if myChoice in [1, 2, 3, 4]:
print(myChoice)

In createList, you are taking the input twice then referring to an undefined variable a
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
...
if any([num < 0 for num in a]):
Exception
should be something like
text_input = input("Give me five numbers: ")
numbers = [int(num) for num in text_input.split(' ')]
if any([num < 0 for num in numbers]):
raise ValueError
Your programme has a number of other oddities, but perhaps you're still working on these:
You don't do anything with the numbers you have input in createList but instead return a list of random numbers. Your description also suggests you want a list of random numbers, so why are you inputting the numbers in the first place?
You make variables myList and newList but your functions won't be able to access these unless you declare them as global or explicitly pass them as parameters
linearSearch can be written more simply using list.index:
.
def linearSearch(myList, target):
if target in myList:
return myList.index(target)
else:
return -1

OK - I found logical and syntax errors at multiple places. I will try to list them as possible.
Commented out redundent block of choices in displayMenu() function.
fixed main() function. You were not catching values/list returned by
functions
Defined myList as global list that needed to be passed
linearSearch(myList,target) had extra user input and tweaked logic
to work. It was only working for finding number at first index.Ideally you can use list.index(value) method to get index #
Commented out extra loop in createList() function
Tweaked functions to receive global list to work properly.
I've tweaked your code as little as possible. Commented out lines not required.
I believe it works as intended.
Working Code:
def main():
myList = []
choice = displayMenu()
while choice != '4':
if choice == '1':
myList =createList()
elif choice == '2':
#print(myList)
displayList(myList)
elif choice == '3':
searchList(myList)
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = str(input("Enter option-->"))
"""
if myChoice != 1 and myChoice != 2 and \
myChoice != 3 and myChoice != 4:
print("Invalid option. Please select again.")
"""
return myChoice
import random
def linearSearch(myList,target):
#target = int(input("--->"))
found = False
for i in range(len(myList)):
if myList[i] == target:
found = True
return i
if found == False:
return -1
#This will generate the five random numbers from 0 to 9
def createList():
print "Creating list..............."
newList = []
"""
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
"""
for i in range(5):
newList.append(random.randint(0,9))
#print newList
return newList
#Option two to display the list
def displayList(myList):
#myList = newList
print("Your list is: ", myList)
#Option 3 to search the list
def searchList(myList):
target = int(input("--->"))
#print("Searching for" , target)
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
Output
>>>
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->1
Creating list...............
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->2
('Your list is: ', [1, 4, 6, 9, 3])
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->4
('Found at', 1)
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->9
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->10
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->10
Not found...
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->4
Thanks for playing!
>>>
Final notes,
You may want to start with something simple such create a menu that prints different sentences for different choices to see if it works and then go as complex as you wish.

Change
myChoice = input("Enter option-->")
to
myChoice = str(input("Enter option-->"))
Function input returns an integer, and comparison with str will allways return False.

Related

While loop to append list or break based on value type and user input

I'm trying to write a python program that asks the user to enter an integer or "q" (case-insensitive) to quit that will then take any integers and print the sum of the last 5.
I have created a holding list and some counter and test variables to help with this, but I can't seem to get it to work the way I'd like. I keep getting various errors.
The code I currently have is
my_list = []
quit = 0
i = 0
while quit == 0:
value = eval(input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit()
my_list.append(value)
i += 1
print(sum(my_list[-1] + my_list[-2] + my_list[-3] + my_list[-4] + my_list[-5]))
if value == q:
quit += 1
elif
print("Your input is not an integer, please try again")
This is returning and error of invalid syntax for the my_list.append(value) line.
What I would like this to do is allow for me to enter any integer, have the loop test if it is an integer, and if so, add it to the holding list and print out the sum of the most recent 5 entries in the list (or all if less than 5). If I enter "q" or "Q" I want the loop to break and the program to end.
There are many errors in your code.
Fixed code:
while quit == False:
value = input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit():
my_list.append(int(value))
i += 1
print(sum(my_list[-5:]))
elif value == 'q' or value == 'Q':
quit = True
else:
print("Your input is not an integer, please try again")
Notes:
Do not use eval, it can be dangerous. As you check if the value contains digit, you can safely use int to cast the value.
If you want to quit with 'q' or 'Q', you have to check both.
You have to slice your list to avoid exception if your list does not contain at least 5 elements.
You can try if this:
*It is shorter and more readable
my_list = []
while True:
x = input("Please enter an integer or the letter 'q' to quit: ")
if x == 'q':
break
else:
my_list.append(int(x))
output_sum = sum(my_list[-5:])
print(output_sum)
Input
1
2
3
4
5
q
Output
15
You should check that the input contains at least 5 digits. You can do this by first checking the length of the input string then calling isnumeric() on the string.
Then you just need to slice the string (last 5 characters) and sum the individual values as follows:
while (n := input("Please enter an integer of at least 5 digits or 'q' to quit: ").lower()) != 'q':
if len(n) > 4 and n.isnumeric():
print(sum(int(v) for v in n[-5:]))
...or if you want to input numerous values then:
numbers = []
while (n := input("Please enter a number or 'q' to quit: ").lower()) != 'q':
if n.isnumeric():
numbers.append(n)
else:
print(f'{n} is not numeric')
if len(numbers) < 5:
print(f'You only entered {len(numbers)} numbers')
else:
print(sum(int(v) for v in numbers[-5:]))

If statement not executing what it should

mylist = []
for i in range(0,101,2):
mylist.append(i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
print(first_half)
print(second_half)
if userRandomNumber in first_half:
print('you got it')
elif userRandomNumber in second_half:
print('you got it')
else:
print('false!')
I am making a program where the user has to guess the number in the random list generated automatically. But the problem is when I run the code and input a number that is actually in the list the if statement does not work the way it should!
What is wrong with the code here? Please help!
input returns a string. So, the number you actually enter is converted to string. Even if it didn't, the str would.
Your lists are full of integers. So there is a difference between an integer and string number. It is checking if the string number is in the list.
Of course, it isn't. So the in operator returns False
input('Please input a random number from 0-100: ')
Try this:
if int(userRandomNumber) in first_half:
print('you got it')
elif int(userRandomNumber) in second_half:
print('you got it')
else:
print('false!')
Here this is code:
number=input("Type a number:")
mylist = []
for i in range(0,101,2):
mylist.insert(1,i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
if int(number) in first_half:
print('you got it')
elif int(number) in second_half:
print('you got it')
else:
print("Nope, "+"'"+"number"+"'"+" not found in the list")
print(first_half)
print(second_half)
In your code, these set of code -
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
can be changed into this -
while True:
try:
userRandomNumber = int(input('Please input a random number from 0-100: '))
break
except:
pass
If you do not know what try and except does, then check this - Python Exception Handling
The rest of the code can be the same, and it will work.
mylist = [i for i in range(0, 101, 2)]
middle_index = len(mylist) // 2
first_half, second_half = mylist[:middle_index], mylist[middle_index:]
print(first_half, second_half, sep='\n')
userRandomNumber = ''
while not userRandomNumber.isdigit():
userRandomNumber = input('Please input a random number from 0-100: ')
userRandomNumber = int(userRandomNumber)
# I think the point of splitting the list into two parts is probably to determine which part belongs to
# the number entered. Otherwise, if the output is 'you got it', then splitting the list makes no sense.
if userRandomNumber in first_half:
print('you got it in the first half')
elif userRandomNumber in second_half:
print('you got it in the second half')
else:
print('false!')

How to create simple menu in Python with list functions?

Please have a look at the exercise that i was asked to do. I am struggling for hours now to make it work.
There has to be a menu with the following choices: add a number, remove number (enter placeholder), show list.
Each time choice is made program should ask if we want to re-run the script.
Tried loops, functions and it just doesn't seem to work with me.
See the code below.
Thank you in advance!
def list():
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
''')
mylist = []
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''
Would you like to see main menu again? (Y/N)
''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()
You can use https://github.com/CITGuru/PyInquirer for than kind of menus.
As the others have pointed out, your mylist variable needs to be moved.
That said, I find that your mechanism of returning to the input query could be refined. See the code below. Here you keep everything in one function, without having to repeatedly ask the user if he/she would like to continue, it continues indefinately until you consciously break out of it.
def main():
mylist = []
while True:
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
[4] Exit programm
''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
elif operation == '4':
break
else:
print("Invalid choice. Please try again.")
main()
Sidebar: "list" is a fixed expression in python. I would refrain from using it and others like it as variable names.
Verified Code
mylist = []
def list():
operation = input('''Select operation:\n [1] Add number to the list \n [2] Remove number from the list \n [3] Display list\n ''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''Would you like to see main menu again? (Y/N)''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()
Cheers!
Try moving mylist = [] outside of the function.

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

Creating a list of five numbers

I'm trying to have Python prompt the user to pick five numbers and store them in the system. So far I have:
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
#This is where I need it to ask the user to give five numbers
def createList():
newList = []
while True:
try:
num = (int(input("Give me five numbers:")))
if num < 0:
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
Once I run the program it allows me to choose option 1 and asks the user to enter five numbers. However if I enter more than one number it says invalid and if I only enter one number it says thank you and displays the menu again. Where am I going wrong?
numbers = [int(x) for x in raw_input("Give me five numbers: ").split()]
This will work assuming the user inputs the numbers separated by blank spaces.
Use raw_input() instead of input().
With Python 2.7 input() evaluates the input as Python code, that is why you got error. raw_input() returns the verbatim string entered by the user. In python 3 you can use input(), raw_input() is gone.
my_input = raw_input("Give me five numbers:") # or input() for Python 3
numbers = [int(num) for num in my_input.split(' ')]
print(numbers)
#DmitryShilyaev has properly diagnosed the problem. If you want to read 5 numbers in a single line, you could use split to split the string that input returns, and convert each element of that list to an int.

Categories