Python Lists: .lower() attribute error - python

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]

Related

Taking user input and appending it to a tuple? Python

So basically I'm trying to create a list of movies with their budgets, but I don't know how to take the input and place it into a tuple
movie_list = ()
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append(title, budget)
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
Tuples don't handle appending well. But lists do:
movie_list = [] # make a list, not a tuple
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
You can’t add elements to a tuple due to their immutable property. You can’t append for tuples.
Tuples are immutable in Python. You cannot add to a tuple.
A tuple is not a data structure like a list or an array. It's meant to hold a group of values together, not a list of the same kind of values.
I think I get what you want, my guess would be that you want a list of tuples. In that case, just change the first line variable to be a list.
I improved your code so your logic works:
movie_list = [] # movie_list is a list
while True:
title = input("Enter movie: ") # Use input() to get user input
budget = input("Enter budget: ")
movie_list.append((title, budget)) # Append a tuple to the list
# movie_list is now a list of tuples
# Check if the user wants to add another movie
more = None
# Loop until the user enters a valid response
while True:
more = input("Add another? (Y/N): ").upper()
if more in ("Y", "N"):
break
print("Invalid input")
# If the user doesn't want to add another movie, break out of the loop
if more == "N":
break
# Else, continue the loop
print(movie_list)
Coding apart, to write any program, first one should know the purpose of the program and its outcome. It would be better, if you can show here what the exact output you want, out of the created or appended list. As far as I understood your requirement, you should go with dictionary concept so that you can store data as pairs, like, movie and its budget.
{"movie":budget}
While taking input of budget, be sure whether you want to restrict the input value to an integer or you want to allow this as a string, like in crores. Hope this will help you.

Validate if its a string or not

I am not getting it right and I can't find how to do it.
Get the user input and create a thematic list of strings. The program should ask for a specific input theme.
The user should enter strings for the list until a condition is met such as entering a specific word or character.
There should not be hard coded list size.?
Each user input should be one list element.
MyList = []
for _ in range(5):
planets = str(input("Enter 5 planets: "))
if planets == str(planets):
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(str(MyList))
I don't quite understand. To validate if something is a string should be isinstance(something, str). But input always returns a string. There is no need to do extra validation.
By the way, if you only want to eliminate duplicated items, I suggest using a set instead of a list. Call str() for print() is also redundant because print() will do the conversion itself. So:
print("Enter 5 planets: ")
result = {input(f"{i}) ") for i in range(1, 6)}
print("That's your planets:", ", ".join(result))
MyList = []
for _ in range(5):
planets = input("Enter 5 planets: ")
if type(planets) == str:
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(",".join(MyList))
Actually any variable defined with the input() function will always be a str data type, because even if it's a number, it would still be the string representation of that number. Even if the user did not input any values ​​at all, it would still be an empty string "".
I'm not sure what kind of verification you are trying to do exactly on that input but if you want to verify that it's not a number you can use theisdigit() string method.
Here is a simple example:
planets = []
while True:
planet = input("Insert the name of a planet: ")
if planet == 'quit':
break
if not planet.isdigit() and not planet in planets:
planets.append(planet)
print("Here is your list of planets:")
for planet in planets:
print(planet)
This block of code continually prompts the user to enter a planet name until the keyword quit is entered. If the input is not a number and is not already in the planets list, it is added. Finally, the complete list of planets is shown.
It must be said that on a conceptual level this implementation does not make much sense. It would be more logical to have a list of all known planets and check if the entered input matches any of the entries in the list. In that case, checking if the string represents a number becomes rather pointless.

Sort an integer list in Python

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_)

lists of list and random choice

The question I need help with is:
Write a program that stores the names of ten countries in column1 and their capitals in column2. The program should then pick a random country and ask the user for the capital.
Display an appropriate message to the user to show whether they are right or wrong.
So far I have
column1 = []
column2 = []
listoflist = [(column1)(column2)]
maxlength = 10
while len (column1) < maxlength:
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
column1.append(country)
column2.append(capital)
for item in done:
print (item[0],item[1])
if anyone can help please.
I believe your list of list setup is a little off for what you intend. Try something like this:
from random import shuffle
data = []
maxlength = 10
while len (data) < maxlength:
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
# for this scenario, probably better to keep rows together instead of columns.
data.append((country, capital)) # using a tuple here. It's like an array, but immutable.
# this will make them come out in a random order!
shuffle(data)
for i in range(maxlength):
country = data[i][0]
capital = data[i][1]
print("Capital for the country {0}?".format(country))
user_said_capital_was = input("What do you think?")
if user_said_capital_was == capital:
print("Correct!")
else:
print("Incorrect!")
You should write this as:
listoflist = [column1, column2]
In your code you're not correctly defining the list of lists and that leads to an error.
import random
dict1 ={"Turkey":"Istanbul","Canada":"Ottawa","China":"Beijing"}
list1=[key for key in dict1.keys()]
try:
q=random.choice(list1)
except:
print ("We are out of countries, sorry!")
while True:
user=input("What is the capital city of {} ?: ".format(q))
if user == dict1[q]:
print ("Correct")
list1.remove(q) #removing first choice so same country never asking again
try:
q=random.choice(list1)
except:
print ("We are out of countries,sorry!")
break
else:
print ("Not correct")
Using dict and key-value system and list comprehension.
A list of lists can work, but a dictionary with key, value pairs works great for this.
In keeping with your original theme of user input, the logic works out well and you can use the random.choice function to pick your country while keeping track.
import random
data = {}
maxlength = 10
for _ in range(maxlength):
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
# using a dict, keeps things simple
data[country] = capital
countries = list(data.keys())
picked = []
while len(picked) < maxlength:
country = random.choice(countries)
if country in picked:
continue
print("Capital for the country {0}?".format(country))
user_said_capital_was = input("What do you think? ")
if user_said_capital_was == data[country]:
print("Correct!")
picked.append(country)
else:
print("Incorrect!")

regarding the use of input().split() with 3+ items

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.

Categories