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.
Related
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.
Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")
I am trying to shorten the process of making lists through the use of a defined function where the variable is the list name. When run, the code skips the user input.
When I run my code, the section of user input seems to be completely skipped over and as such it just prints an empty list. I've tried messing around with the variable names and defining things at different points in the code. Am I missing a general rule of Python or is there an obvious error in my code I'm missing?
def list_creation(list_name):
list_name = []
num = 0
while num != "end":
return(list_name)
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
list_creation(list_Alpha)
print("This is the first list: " + str(list_Alpha))
list_creation(list_Beta)
print("This is the second list: " + str(list_Beta))
I want the two seperate lists to print out the numbers that the user has input. Currently it just prints out two empty lists.
You need to move the return statement to the end of the function, because return always stops function execution.
Also, what you're trying to do (to my knowledge) is not possible or practical. You can't assign a variable by making it an argument in a function, you instead should remove the parameter list_name altogether since you immediately reassign it anyway, and call it like list_alpha = list_creation()
As a side note, the user probably wants to see the whole "To end, type end as number input" bit before they start giving input.
Dynamically defining your variable names is ill advised. With that being said, the following code should do the trick. The problem consisted of a misplaced return statement and confusion of variable name with the variable itself.
def list_creation(list_name):
g[list_name] = []
num = 0
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
g[list_name].append(num)
g = globals()
list_creation('list_Alpha')
print("This is the first list: " + str(list_Alpha))
list_creation('list_Beta')
print("This is the second list: " + str(list_Beta))
There are a couple of fundamental flaws in your code.
You redefine list_name which is what Alpha and Beta lists are using as the return.(list_name = [] disassociates it with Alpha and Beta so your function becomes useless.)
You return from the function right after starting your while loop(so you will never reach the input)
In your function:
list_Alpha = []
list_Beta = []
def list_creation(list_name):
# list_name = [] <-- is no longer Alpha or Beta, get rid of this!
num = 0
...
The return should go at the end of the while loop in order to reach your input:
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
return(list_name)
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 was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)