Having trouble with giving strings values (Python) - python

For School I am meant to create a program that identifies your mood and then tells you what it really is. Anyway with my code I keep getting errors about the way I have assigned values to my strings. Currently my code looks like this:
import random
smiles = ['XD',';)',':)',':()',':(']
history = []
reality = random.choice(smiles)
('XD')= 5
(':)') = 4
(':|') = 3
(':T') = 2
(':(') = 1
def menu():
print (smiles)
int(input("Which emoticon do you relate to?"))
if 1:
print("You are Fealing like XD")
print("but in reality you are feeling like", reality)
etc
Thanks.

As said in the comments, you cannot assign a value to a string, you need to store them in a type of a collection, dictionary or list etc.
Given that you're asking for a number from the user, you can just assign the users input to a variable then compare that against the index in the array. Feel free to add error handling here for an input that is outside the length of the array.
int(input("Which emoticon do you relate to?"))
if 1:
could be
user_input = int(input("Which emoticon do you relate to?"))
if user_input - 1 == 0: # -1 since lists are 0 indexed.
You could make this generic as well and remove the if statement and just use
users_smile = smiles[user_input - 1]
print("You are Fealing like {}".format(users_smile))

You can't assign value to string as #juanpa.arrivillaga said so you should use dictionary
smiles_dict = { 5: 'XD', 4: ':)', 3: ':|', 2: ':T', 1: ':(' }
and then use
smiles_dict.get(reality)
hope this might help you

Related

How to assign strings in a list to another string as a 'shortcut'?

Clarification: The user needs to specify an ID from a displayed list of ID's, how can I simplify the process by numbering the ID's so that the user just has to specify a simple number instead of the whole ID
I have a list ID = ['ekjgnrg','lrkjnk','etc..'] that I need to interact with by inputting the ID later on. The issue is it's a little tedious to type it in. (Copy-pasting would solve this but it doesn't work on mobile due to the way the message with the list is displayed.)
How can I assign a number to each string in the list so that the user can enter '1' instead of 'ekjgnrg' for simplicity? The list gets longer and shorter occasionally, so how can I make it scale to the size of the list?
Not sure how you present to user, but, you can do something like:
ID = ['ekjgnrg', 'lrkjnk', 'etc..']
print('Choose one of:')
for n,item in enumerate(ID):
print(f'{n}: {item}')
n = int(input('Enter ID number: '))
print(f'You choose number "{n}" which is "{ID[n]}".')
This really needs error checking, like gracefully handling if someone enters invalid data like "foo" or "1000"...
Results in:
Choose one of:
0: ekjgnrg
1: lrkjnk
2: etc..
Enter ID number: 1
You choose number "1" which is "lrkjnk".
You can access the Nth item using my_list[n] (in your case my_list is ID).
I suggest you to read: Python - Access List Items - W3Schools to understand how to work with list or other data structure in Python.
is this what you mean? if not, please elaborate more.
ID = ['ekjgnrg','lrkjnk','etc..']
print(ID)
needed_id = int(input("What item do you want from the above list?"))
needed_id -= 1 # since lists start at 0.
print(ID[needed_id])
when run:
['ekjgnrg', 'lrkjnk', 'etc..']
What item do you want from the above list?1
ekjgnrg

allowing user to select from a list using the index location

My apologies up front if I haven't asked this question correctly, it is my first time asking here.
I have a script that works currently, but I am trying to improve it.
I create a dictionary of days of the week and against each value I allow the user to input which meal they would like to eat on that day. However, at present I require the use to type their selected option from a list, which must match exactly. for instance "Szechuan pork stir-fry" - it is easy to make a typo here. Rather than manage the typo i'd like to make it easier for the use to make their selection from the list e.g. by selecting a key from a dictionary or an index location from the list - I am having trouble getting either of those to work though.
my code looks like this right now:
for d in week_meals:
try:
answer = input(f"What would you like to eat on {d}? options are {week_meals_list}")
week_meals_list.remove(answer)
week_meals[d] = answer
except ValueError:
print("That isn't an option!")
answer = input(f"What would you like to eat on {d}? options are {week_meals_list} type {week_meals_list.index")
week_meals_list.remove(answer)
week_meals[d] = answer
I have tried to create a dictionary by doing something like the below but I cannot figure out how to set the key for each item to increment up by 1:
week_meals_dict = {}
for k in range(int(days)):
week_meals_dict[k] = None
but then I really cannot figure out a way to iterate through each key while simultaneously iterating through a list in parallel. is this even possible?
this got me thinking it might be easier to just ask the user to input the index location within the list but I can't figure that out either.
I figured it out...
not really sure I fully understand why it works but this does seem to:
for k in range(int(days)):
week_meals_dict[k] = week_meals_list[k]
I can maybe even clean this up but I am happy with it for now
week_meals = {}
week_meals_list = ['meal1', 'meal2',]
for d in range(1, 8):
meal = None
while not meal:
answer = input(f"What would you like to eat on {d}? options are {week_meals_list}")
try:
meal = week_meals_list[int(answer)]
week_meals_list.remove(meal)
week_meals[d] = meal
except (IndexError, ValueError):
pass
First of all, don't modify a list during iteration.
It seems you're trying to match a meal for each day of the week.
You can iterate on the days:
week_meals_options = {1: "Chicken", 2: "Soup"} # Your dict containing choices mapped to the meal options
week_meals = {}
for day in week_days:
while True:
answer = input(f"What would you like to eat on {day}? options are {week_meals_options.keys()}")
if answer in week_meals_options:
week_meals[d] = week_meals_options.pop(answer) # Remove the option from the dict, and assign it to the day
break
else:
print("That isn't an option!")

Add more values in a list at once in Python

I'm a beginner in Python and I'm trying to solve this problem.
I'm trying to write a code where you can put your name and the amount that you want to donate.
The thing is, deppending on the amount of the donation you can have more chances to be the winner.
Eg. If you donate $10 (1 chance), $20(2 chances), $30(3 chances).
My biggest problem is because I can't figure out how to solve this problem when the person insert $30 its name goes to the list 3 times and so on. I tried to use "for..inrange():" but without any sucess. Can someone explain me how to do this?
from random import shuffle
from random import choice
list = []
while True:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
list.append(name)
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 1:
continue
else:
shuffle(list)
winner = choice(list)
break
print('The winner was: {}' .format(winner))
First do not use the name of a built-in type as a (meaningless) variable name. Change list to entry_list.
For the particular problem
compute the quantity of chances;
make a list of the person's name that many times;
extend the entry list with that list of repeated name.
Code:
entry_list = []
while ...
...
chances = int(donation) // 10
entry_list.extend( [name] * chances )
An alternative to adding another loop with additional control flow, you can use list.extend() with a list expression:
num_chances = donation // 10
chances = [name] * num_chances
all_chances.extend(chances)
Note that list is a built-in python identifier, and it's not a good idea to overwrite it. I've used all_chances instead.
Rather than adding extra names to the list to represent the higher chance, you could use the donations as weights in the random.choices function:
from random import choices
names, donations = [], []
while True:
names.append(input('Write your name: '))
donations.append(float(input('Enter the amount you want to donate.: $')))
print(f'You donated ${donations[-1]}. Thank you {names[-1]} for your donation!')
print('=-'*25)
print('[1] YES')
print('[2] NO')
if input('Would you like to make another donation? ') != '1':
break
winner = choices(names, donations)[0]
print(f'The winner was: {winner}')
This allows for non-integer donations to be counted fairly -- e.g. if Bob donates $0.25 and Fred donates $0.50, the drawing will still work in a reasonable way. It also allows very large donations to be handled without tanking the performance of the program -- if you have one list entry per dollar donated, what happens if Elon donates $20B and Jeff donates $30B? (The answer is that your fan spins really fast for a while and then the program crashes because you can't create a list with 50 billion elements -- but this is not a problem if you simply have a list of two elements with large int values.)
Note that shuffle is not necessary if you're using random.choices (or random.choice for that matter) because those functions will already make a random selection from the list.
You can use a for loop to append the name to the list more than one time :
for i in range(donation//10):
list.append(name)
This code should do the job. Please follow good naming conventions as pointed out by others. I have changed the list variable to donations as it is forbidden to use keywords as variables.
I have included the name in donations int(name) // 10 times using the extend function as pointed out by others. You may change the number of times as you wish.
from random import shuffle
from random import choice
donations = []
makeDonation = True
winner = "Unknown"
while makeDonation:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
donations.extend([name for i in range ( int(donation) // 10)])
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 2:
makeDonation = False
shuffle(donations)
winner = choice(donations)
print('The winner was: {}' .format(winner))

Turning a list number, into another value that is returned [python]

I am currently working on this code:
def N_C(question,choice):
N_C_choice_count_max = len(choice)
N_C_choice_count_min = N_C_choice_count_max - N_C_choice_count_max
N_C_restart_input = True
N_C_choices = []
print(question)
for i in range (N_C_choice_count_min,N_C_choice_count_max):
print(N_C_choice_count_min+i+1,":",choice[i])
str(N_C_choices.append(N_C_choice_count_min+i+1))
while N_C_restart_input == True:
N_C_input = input(">")
if str(N_C_input) in str(N_C_choices):
break
else:
continue
return(N_C_input)
N_C("question",["choice1","choice2","asmanychoicesasyouwant"])
And it works fine as it is, but to select a choice you input the number of the choice, which makes sense, but I would like for it to instead return the number they choose, the actual choice that goes with that number.
I am thinking that maybe something with a dictionary could work, or even just using the choice list provided, but I cannot figure it out, and help is appreciated.
choice is a list containing all the answers and N_C_input is a number as a string, which is associated to choice.
return choice[int(N_C_input)-1]
Returns the actual choice.

Using if/elif/else for a "switch" in python

While using the following code:
url = None
print("For 'The Survey of Cornwall,' press 1")
print("For 'The Adventures of Sherlock Holmes,' press 2")
print("For 'Pride and Prejudice,' press 3")
n = input("Which do you choose?")
if n==1:
url = 'http://www.gutenberg.org/cache/epub/9878/pg9878.txt' #cornwall
print("cornwall")
elif n==2:
url = 'http://www.gutenberg.org/cache/epub/1661/pg1661.txt' #holmes
print("holmes)
elif n==3:
url = 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt' #pap
print("PaP")
else:
print("That was not one of the choices")
I'm only getting the "else" case returned, why might that be??
input() returns a string in py3x. So, you need to convert it to int first.
n = int(input("Which do you choose?"))
Demo:
>>> '1' == 1
False
>>> int('1') == 1
True
input() returns a string, but you are comparing it to integers. You can convert the result from input to an integer with the int() function.
You should convert the input with int()
n = input("Which do you choose?") should be n = int(input("Which do you choose?"))
This is due to the fact that input returns strings for all input since it should almost always work.
I'm guessing you are using Python 3, in which input behaves like raw_input did in Python 2, that is, it returns the input value as a string. In Python, '1' does not equal 1. You'll have to convert the input string to an int using n = int(n), then go through your succession of elifs.
input() returns a string type. So, you need to convert your input into an integer using int(), or else you can compare the inputs to characters instead of integers, like '1', '2'.
While the other answers correctly identify the reason you're getting the else block in your current code, I want to suggest an alternative implementation that is a bit more "Pythonic". Rather than a bunch of nested if/elif statements, use a dictionary lookup, which can support arbitrary keys (including perhaps more meaningful ones than integers):
book_urls = {'cornwall': 'http://www.gutenberg.org/cache/epub/9878/pg9878.txt',
'holmes': 'http://www.gutenberg.org/cache/epub/1661/pg1661.txt',
'p and p': 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt'}
print("For 'The Survey of Cornwall,' type 'cornwall'")
print("For 'The Adventures of Sherlock Holmes,' type 'holmes'")
print("For 'Pride and Prejudice,' type 'p and p'")
choice = input("Which do you choose?") # no conversion, we want a string!
try:
url = book_urls[choice]
except KeyError:
print("That was not one of the choices")
url = None
You could make the whole thing data-driven if you wanted, with the book names and urls being provided as an argument to a function that would ask the user to pick one (without knowing what they were ahead of time).

Categories