Creating a list of five numbers - python

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.

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:]))

How to return to menu by a special key?

Is there any simple method to return to menu by entering a special key? If the user made a mistake while entering the input, user can return to main menu by pressing # (a special key) key at the end of the input.
x = input("Enter first number: ")
Here, user enter 5, but want to exit by input #. So, x = 5#
I tried some including this
x=input("Enter first number: ")
print(int(a))
if x == "#":
exit()
Also tries this too
for x in ['0', '0$']:
if '0$' in x:
break
But, unable to handle numbers and string values together.
while True:
x = input()
if x[-1] == '#':
continue
# other stuff
this should work
Try
user_input = input("Enter your favirote deal:")
last_ch = user_input[-1]
if(last_ch == "#"):
continue
else:
//Your Logic
int(x) will not work if it contains characters other than numbers.
use this construction (# will be ignored by converting a string to int)
x=input("Enter first number: ")
print(int(x if "#" not in x else x[:-1])) # minus last if has #
if "#" in x:
exit() # or break or return, depends what you want

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.

Input from keyboard the <enter>

I use Python 3 in Windows. My problem is that I need to find out how can I put in my code the choice that if the user pushes the Enter key the program will continue doing the calculation and when the user types q and pushes the Enter key the program will be terminated.
A simple code is below.
while True:
x = int(input('Give number: '))
y=x*3
print(y)
while True:
user_input = input('Give number: ')
if not user_input.isdigit(): #alternatively if user_input != 'q'
break
x = int(user_input)
y=x*3
print(y)
Assuming you want to calculate while new numbers are entered, the str isdigit function returns True if the string only contains digits. This approach will allow you to handle if the user enters a non-integer like xsd, which will crash the program if you try to cast to int. To only exit if q is entered, you would do if user_input != 'q', but this assumes the user only enters numbers or q.
while True:
s = input('Give number: ')
if s == 'q':
break
y=int(s)*3
print(y)

error when validating user input

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.

Categories