« on: October 31, 2014, 01:07:08 pm »
I'm trying to make a function that will append an item to a list based on user input. Python 2.7.8, Windows 7.
# Lab 4.1 Create five separate lists. Each list should have a theme and the The prompts work fine but the output is:
# theme should be reflected in the list name and its elements. Examples are:
# pets = ['dog', 'cat', 'rat']
# numbers= [34, -1232, 456, 2134]
weather = ['Clear','Rain','Snow','Storm','Windy','Hail','Fog']
locations = ['Park','Forest','Beach','River','Library','Cafe','College',
actions = ['Walk','Examine','Activate','Talk','Wait','Eat','Sleep','Read',
day = ['Morning','Mid-day','Afternoon','Evening','Twilight','Night',
animals = ['fish','Crow','Deer','Seagull','Mosquito','Racoon','Skunk',
# Lab 4.2 Using the lists you defined in 4.1, define functions that
# demonstrate your knowleldge of the list functions: append, extend,
# remove, pop, index, sort, and reverse. Write at least 2 examples
# using each function.
listName = raw_input('You choose to append an item to a list.\nFirst we'
' must select a list.\nType the name of one of these lists to see its'
' elements:\nweather, locations, actions, day, or animals.\n'
'Which list do you want to view? ')
# ^get name of list to append an element
if listName == 'weather':
for i in weather:
elif listName == 'locations':
for i in locations:
elif listName == 'actions':
for i in actions:
elif listName == 'day':
for i in day:
elif listName == 'animals':
for i in animals:
# ^print all the elements in the selected list
print 'There is no list available under that name!'
# ^print if user mistypes name of list
appendElement = str(raw_input('Please type the element you wish to append to'
' the selected list: '))
# ^get the element user wants to append to list
newList = listName + '.append(\'' + appendElement + '\')'
Please type the element you wish to append to the selected list: Sandstorm
What am I doing wrong?
I guess what I want to do is use input to get parts of code and then execute that code. I know that it's a really stupid idea because that means that users can execute code but still you'd think there would be a way to concatenate string literals and variables that are also strings together and then execute them as code.