I'm currently working on a program that deals with user input and I came across a situation where I needed multiple returns under one input(), at first I didn't know what I was doing when I was getting a value error until I looked up how to do it, which it showed me and worked fine with 2 inputs with input().split()
class userinput():
def __init__(self, name,lista,listb,listc,listd):
self.name=""
self.lista=lista
self.listb=listb
self.listc=listc
self.listd=listd
def set_lists(self):
print("Do you want to create lists")
decision = input()
if decision == "yes":
print("how many lists would you like to create?(up to 4)")
decision2= int(input())
if decision2 == 1:
print("what would you like the list to be named")
self.lista=input()
print("you have created 1 list, with the name:"+ self.lista)
elif decision2 == 2:
print("what would you like your lists to be?")
self.lista,self.listb=input().split(",")
print("You have created 2 lists with the names," + self.lista ,self.listb)
elif decision2 == 3:
print("what name would you like your first 2 lists to be")
self.lista,self.listb = input().split(",")
print("finally, the name for your third")
self.listc = input()
print("you have created 3 lists with the names," +self.lista,self.listb,self.listc)
elif decision2 == 4:
print("what name would you like your first 2 lists to be")
self.lista,self.listb = input().split(",")
print("finally, for your last 2 lists")
self.listc,self.listd=input().split(",")
print("you have created three lists with the names of," +self.lista,self.listb,self.listc,self.listd)
else:
print("quitting")
return
else:
print("quitting")
My Question: it seems as if it isn't necessary to use 2 input().split() for 4 inputs, Is there anyway to clean that up?
You have a couple of problems, and a lot of duplication here. An approach with a couple of improvements:
decision = input("Do you want to create lists?")
if decision.lower() in ("y", "yes"):
list_count = int(input("How many lists?"))
names = input("Enter list names (separated by commas):").split(",")
if len(names) != list_count:
raise ValueError("Expected {0} names, got {1}".format(list_count,
len(names)))
self.lists = {name: [] for name in names} # dictionary of empty lists
print("Created {0} lists.".format(list_count))
(Note that Python 2.x uses raw_input).
split creates a list of as many items as the string could be split into, unless constrained by a second, optional argument maxsplit:
"a,b,c".split(",") == ["a", "b", "c"]
"a,b,c".split(",", 1) == ["a", "b,c"]
I think this code would be a bit cleaner.
print("Do you want to create lists")
decision = input()
if decision == "yes":
print("how many lists would you like to create?(up to 4)")
decision2= int(input())
print("What would you like the lists named?")
listnames = input()
lists = listnames.split()
print("you have created %i lists with the following names: %s"%(decision2, ",".join(lists)))
else:
print("quitting")
a, b, c, d = raw_input("what name would you like your 4 lists to be\n").split(',')
split can split string into more than two parts.
I'd just do this:
def set_lists(self):
print("Do you want to create lists")
decision = input()
if decision.lower().startswith("y"):
print("how many lists would you like to create? (up to 4)")
decision2 = int(input())
if decision2 == 1:
print("what would you like the list to be named")
self.lists = [input()]
print("you have created 1 list, with the name:"+ self.lists[0])
elif 2 <= decision2 <= 4:
print("Enter your lists' names, seperated by commas")
self.lists = input().split(",")
if len(self.lists) != decision2:
print("You didn't enter the right amount of names!")
else:
print("You have created {} lists with the names {}".format(decision2, ", ".join(map(str, self.lists)))
else:
print("quitting")
else:
print("quitting")
And then do self.lists[0], self.lists[1] etc. rather than self.lista, self.listb.
Related
New to programming and not sure how to print if the users answer to the list questions is correct or not and then add it to their ongoing score which will be displayed at the end of the program.
#number list test program
import random
import statistics
choosequestion = random.randint(1,4)
print('Welcome to the number list test')
print('e) Easy')
print('m) Medium')
print('h) Hard')
difficulty = input('Difficulty: ')
if difficulty == 'e':
print('Easy difficulty selected')
score = 0
questions = 2
quantity = 3
minimum = 1
maximum = 5
lists = random.sample(range(minimum, maximum), quantity)
if choosequestion == 1:
print ('What is the smallest number in this list?', lists)
finalmin = min = int(input(""))
elif choosequestion == 2:
print ('What is the biggest number in this list?', lists)
finalmax = max = int(input(""))
elif choosequestion == 3:
print ('What is the sum of numbers in this list?', lists)
finalsum = sum = int(input(""))
elif choosequestion == 4:
print ('What is the average of the numbers in this list?', lists)
average = statistics.mean = int(input(""))
##elif difficulty == 'm':
## print('Medium difficulty selected')
##
##elif difficulty == 'h':
## print ('Medium difficulty selected')
Any help will be great, thanks (when running the program select 'e' to start, I've commented out all other options)
Use for loops to ask questions repetitively.
As user enters answer, calculate the real answer in program and compare the result, to score.
You can refer below code.
#number list test program
import random
import statistics
choosequestion = random.randint(1,4)
print('Welcome to the number list test')
print('e) Easy')
print('m) Medium')
print('h) Hard')
difficulty = input('Difficulty: ')
if difficulty == 'e':
print('Easy difficulty selected')
score = 0
questions = 2
quantity = 3
minimum = 1
maximum = 5
for i in range(0,questions):
lists = random.sample(range(minimum, maximum), quantity)
if choosequestion == 1:
print ('What is the smallest number in this list?', lists)
if int(input(""))==min(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 2:
print ('What is the biggest number in this list?', lists)
if int(input(""))==max(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 3:
print ('What is the sum of numbers in this list?', lists)
if int(input(""))==sum(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 4:
print ('What is the average of the numbers in this list?', lists)
if int(input(""))==sum(lists)/len(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
print("Your final score is : "+str(score))
The input() function in python returns a string of what the user types in a console. You can then compare the input string with the correct answer with an equal operator ==. (True if it matches, of course) I've finished a couple lines of code to demonstrate:
#Ask the User the Question
print ('What is the smallest number in this list?', lists)
#Get the User's response
userAnswer = int(input(""))
#Compare the response with the right answer
if(userAnswer == min(lists)):
#User was right
print("Correct")
score += 1
else:
#User was wrong
print("Wrong")
Change the min() function to max(), sum(), or your own function to get the right answer for each question.
For the future, many things could help improve this code:
Comment your code to give a main idea of what it is doing. I'm not talking one comment for each line, just a summary of sections of code.
When using an user input in any language, make sure to stress test it. The int(input("")) crashes the program when the user inputs a string.
Take advantage of functions, loops, and variables. I've seen programmers go down the rabbit hole of using if else statements too much. Do not avoid if else statements necessarily, but use patterns in answers and code to your advantage.
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.
I'm a beginner programmer and I'm trying to make an exercise.
I want to sort an integer list, but every time I run my code the list is not sorted. I've tried it in a couple of different ways with sorted() or .sort() but nothings seems to help.
def main():
_list1_ = []
_list2_ = []
print("Enter random numbers and enter Q to quit: ")
userInput1 = input("")
while userInput1.upper() != "Q":
_list1_.append(int(userInput1))
userInput1 = input("")
print("Enter random numbers and enter Q to quit:")
userInput2 = input("")
while userInput2.upper() != "Q":
_list2_.append(int(userInput2))
userInput2 = input("")
sorted(_list1_)
sorted(_list2_)
print(_list1_)
main()
Thanks!
sorted() doesn't sort the list in place. It returns the sorted list, so you will need to change the 2 sorted() calls to something like this:
_list1_ = sorted(_list1_)
_list2_ = sorted(_list2_)
It's always a good idea to read the documentation to get an understanding for how the functions work. Here is the docs for sorted
https://docs.python.org/2/library/functions.html#sorted
sorted returns the sorted list whereas sort performs the sort in place.
So you could either do:
_list1_ = sorted(_list_)
or:
_list1_.sort()
If you were to use sort (my preferred method) your code would look like this:
def main():
_list1_ = []
_list2_ = []
print("Enter random numbers and enter Q to quit: ")
userInput1 = input("")
while userInput1.upper() != "Q":
_list1_.append(int(userInput1))
userInput1 = input("")
print("Enter random numbers and enter Q to quit:")
userInput2 = input("")
while userInput2.upper() != "Q":
_list2_.append(int(userInput2))
userInput2 = input("")
_list1_.sort()
_list2_.sort()
print(_list1_)
main()
sorted(_list1_)
returns a list after sorting list1, It does not sort the list1. so write
print(sorted(_list1_))
or assign the sorted list1 to list1, like
_list1_ = sorted(_list1_)
I am trying to create a program on python to do with manipulating lists/arrays. I am having trouble with an error:
lowercase = names.lower
AttributeError: 'list' object has no attribute 'lower'
I really need some help to fix this!
names = [] #Declares an array
print("Type menu(), to begin")
def menu():
print("----------------------------MENU-----------------------------")
print("Type: main() for core functions")
print("Type: delete() to delete a name")
print("Type: save() to save the code")
print("Type: load() to load the saved array")
print("Type: lower() to make all items in the list lower case")
print("-------------------------------------------------------------")
def main():
times = int(input("How many names do you want in the array? ")) #Asks the user how many names they want in the array
for i in range(times):
names.append(input("Enter a name ")) #Creates a for loop that runs for the amount of times the user requested, it asks the user to enter the names
choice = input("Would you like the array printed backwards? ") #asks the user whether they want the array backwards
if choice == "Yes":
names.reverse() #If the user says yes, the array is reversed then printed backwards
print(names)
else:
print(names) #Otherwise, the array is printed normally
number = int(input("Which item would you like to print out? "))
number = number - 1
print(names[number])
start = int(input("What is the first position of the range of items to print out? "))
start = start - 1
end = int(input("What is the last position of the range of items to print out? "))
print(names[start:end])
def delete():
takeAway = input("Which name would you like to remove? ")
names.remove(takeAway)
print(names)
def save():
saving1 = open("Save.txt", 'w')
ifsave = input("Would you like to save the array? ")
if ifsave == "Yes":
for name in names:
saving1.write("%s\n" % name)
saving1.close
else:
menu()
def load():
loadquestion = input("Would you like to load a list of names? ")
if loadquestion == "Yes":
saving1 = open('Save.txt', 'r')
print(saving1.read())
saving1.close()
else:
menu()
def lower():
lowerq = input("Would you like to make the array lowercase? ")
if lowerq == "Yes":
lowercase = names.lower
print(lowercase)
else:
menu()
The variable names is a list. You can't use the .lower() method on a list.
pp_ provided the solution:
lowercase = [x.lower() for x in names]
While not exactly equivalent to the previous example, this may read better to you and has, effectively, the same result:
lowercase=[]
for name in names:
lowercase.append(name.lower())
Alternate solution that may fit your needs:
print (str(names).lower())
Like the error message says, you can't use .lower() on lists, only on strings. That means you'll have to iterate over the list and use .lower() on every list item:
lowercase = [x.lower() for x in names]
I'm trying to delete a tuple from my list, I've tried everything people have said but still no luck. I tried two methods, one time it removes the record even if it's not the name I want to remove, and the second doesn't remove at all.
record=[]
newrecord=[]
full_time=""
choice = ""
while (choice != "x"):
print()
print("a. Add a new employee")
print("b. Display all employees")
print("c. Search for an employee record")
print("d. Delete an employee record")
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
for d in record:
if d == delete:
record.remove(delete)
This doesn't remove anything.
If I change it to:
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
record = [n for n in record if delete in record]
It removes all if I do it this way.
Heres how i add to the list
choice = input("Choose an option (a to f) or x to Exit: ")
if choice == "a":
full_name = str(input("Enter your name: ")).title()
job_title = str(input("Enter your job title: ")).title()
while full_time.capitalize() != "Y" or full_time.capitalize() != "N":
full_time=input("Do you work full time (Y/N): ").upper()
if full_time.capitalize() == "Y":
break
elif full_time.capitalize() == "N":
break
break
hourly_rate = float(input("Enter your hourly rate: £"))
number_years = int(input("Enter the number of full years service: "))
record.append((full_name, job_title, full_time, "%.2f" % hourly_rate, number_years))
Given that the name is the first element in the record any checks against the name must be done against the first element of the tuple.
Previously you had:
record = [n for n in record if delete in record]
The first problem here is that you have to check against n and not record in your condition:
record = [n for n in record if delete in n]
The next issue is that this will only add a record to the list if delete is found within it.
It seems as though you want the inverse of this:
record = [n for n in record if delete not in n]
^^^
Now that in itself will not work because delete is a string and n is a tuple here, so we must combine this with the first fix. We then get:
record = [n for n in record if delete not in n[0]]
One thing I would note however is that if you are only using employee names as indexes it's probably much cleaner/easier to just use a dictionary with the employee name as keys and the other information as values. Given that a dictionary is an associative mapping between keys and values and your problem is exactly that I'd recommend changing your data structures.