This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 4 months ago.
I am trying to make my function take an name from the user which would check if the name is in a whitelist before executing a function that prints draws out information from a pre-defined list of the same name but the entered input is being processed as a string by the function instead of the name of the list. How do I get it to take in the input as the name of the list?
hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]
universe = ["hydrogen", "helium"]
elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "
def printelement(element):
print(f" \n-------------------------")
print(elementname_print + element[0])
print(elementsymbol_print + element[1])
print(atomicnumber_print + element[2])
print(relativeatomicmass_print + element[3])
print("-------------------------")
userinput = input("-->")
if userinput in universe:
printelement(userinput)
else:
print("Sorry that element cannot be found.")
Result:
--> hydrogen
Element Name: h
Element Symbol: y
Atomic Number: d
Relative Atomic Mass: r
You should, rather than defining your elements in global scope as hydrogen = ..., define them inside a dictionary keyed by their name.
elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
"helium": ["Helium", "He", "2", "4.0"]}
the lookup then becomes much easier.
def print_element(element_name):
element = elements[element_name]
# the rest as written
Note that you can clean up your code quite a bit:
elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
"helium": ["Helium", "He", "2", "4.0"]}
def print_element(element_name):
element = elements[element_name]
name, symbol, number, mass = element
print(f"""
----------------------
Element Name: {name}
Element Symbol: {symbol}
Atomic Number: {number}
Relative Atomic Mass: {mass}
----------------------""")
userinput = input("-->")
if userinput in elements:
print_element(userinput)
else:
print("Sorry that element cannot be found.")
There are ways to make your chosen solution work (eval will do it, but introduce huge security risks. globals() will do it, but introduce a large performance overhead), but they're all ugly. Writing an ugly hack is objectively worse than using the right approach in the first place
You can eval the string input to the corresponding variable :
printelement(eval(userinput))
Rest code remains the same.
P.S : This is a quick hack, using eval is unsafe.
Basically your need to get a list corresponding to the user input. Use globals():
lst = globals()[userinput]
So in your example, if user types in 'hydrogen', this will give the list hydrogen. Now do your printings.
Complete example:
hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]
universe = ["hydrogen", "helium"]
elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "
def printelement(element):
print(f" \n-------------------------")
print(elementname_print + element[0])
print(elementsymbol_print + element[1])
print(atomicnumber_print + element[2])
print(relativeatomicmass_print + element[3])
print("-------------------------")
userinput = input("-->")
if userinput in universe:
lst = globals()[userinput]
printelement(lst)
else:
print("Sorry that element cannot be found.")
Related
I am coding a to-do app, but while matching the menu() function it gives a Syntax Error, the function returns the number of the option the user selected, this is the code:
# Imports
import time, os, random
from colorama import Fore, Back, Style
# Functions
def menu():
print(f"{Fore.BLUE}To-Do List!")
print(Style.RESET_ALL)
print(f"{Fore.GREEN}[1] ADD ITEM")
print(f"{Fore.RED}[2] REMOVE ITEM")
print(f"{Fore.BLUE}[3] SEE LIST")
option = int(input("Selection > "))
return option
# Variables
newItem = {
"name": "",
"description": "",
"date": "",
"priority": ""
}
todo = []
# Code
match menu():
case 1:
os.system("clear")
print(f"{Fore.GREEN}ADD ITEM TO LIST")
print(Style.RESET_ALL)
newItem["name"] = input("Item name > ")
newItem["description"] = input("Item description > ")
newItem["date"] = input("Item date > ")
newItem["priority"] = input("Item priority (low/med/high) > ")
todo.append(newItem)
print(todo)
input()
How can I solve it?
I tried changing the variable and using the match() statement a different way, it still has the same error.
As #CryptoFool allready mentioned in the comments, the match statement was added in python 3.10. Means, previous versions won't work.
Make shure to install a python version greater or equeal as 3.10, or use a workaround
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in ().
def main():
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
#if symbol not >,<,=:
print("please use >,<,=")
return
if rating not -5,-3,0,1,3:
print("please use -5,-3,0,1,3")
return
if name = []:
print('no books found')
return
You can use the not in construct to check if an item is not in a list/tuple/other container. Thus, you can do this:
item = "foo"
print(item not in ["foo", "bar", "baz"]) # False
print(item not in ["ham", "egg", "pan"]) # True
This works for numbers too. However, using sets (with curly braces) is more efficient if all you're doing is testing if an item is in the container. Also, I see your code has
if name = []:
When testing for equality in an if statment, use the equals operator ==. Thus your code will be:
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
if symbol not in {">", "<", "="}:
print("please use >,<,=")
return
if rating not in {-5, -3, 0, 1, 3}:
print("please use -5,-3,0,1,3")
return
if name == []:
print('no books found')
return
Finally, the line
if name not in "ratings.txt":
does not check if name is in the contents of the file ratings.txt, but rather if it is a substring of that filename. For checking the file contents, you can try this question.
I am trying to make an easy tic tac toe game in python, but I am currently stuck at changing the list that is used to change the grid to my problem:
grid = [" ", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
def grids():
print(grid[1] + " | " + grid[2] + " | " + grid[3])
print(grid[4] + " | " + grid[5] + " | " + grid[6])
print(grid[7] + " | " + grid[8] + " | " + grid[9])
.....
# picked is what ive selected ( X or O )
while True:
grids()
choose = input(f"choose a number and place your {picked}:")
if isinstance(choose, int) not in grid and choose not in grid:
print("wrong input, try again")
else:
grid[choose] = grid[choose].replace(grid[choose], picked)
(not 100% sure if the last part is correct, I changed so much the last hour that I don't know if it is even working)
I made it work before, the grid list got changed the way I liked it to.
but only if I changed the input = ..to int(input)=..
But as soon as I typed a string as an input (like "d") it crashed and don't know what to do against it. I tried the try/except function as well without any luck.
If you are looking for the way to find input type then you can use String.isnumeric.
def until_user_enters_a_number():
clear = False
entered = 0
while not clear:
entered = input('I\'m going no where before you enter a number: ');
clear = entered.isnumeric()
# make sure the number is between 0 and 9
# may be you also want to make sure the number wasn't selected once already
return int(entered)
This will keep the user in a loop until he enters a valid input, you can add more assertions in it as well.
I am trying to create a basic online store in python. But whenever I try to 'buy' an item it shows an error with my dictionary or something I am not sure.
The error: users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
TypeError: str() takes at most 3 arguments (6 given)
coun = 0
users = [{"name":"Jack","username":"ja", "cc":'12345',"email":'whwhwwhh', "code": '111', "Transactions": ""}]
def sign_in():
username = input("Enter username")
for i in range (len(users)):
for x in users[i].values():
if x == username:
pin = input("Enter pin")
if pin == users[i].get("code"):
print("Welcome", users[i].get("name"))
menu(username,users[i].get("name"))
break
else:
print("Wrong pin")
sign_in()
def menu (usern, names_f):
global coun
if coun == 0:
order = ''
total = 0
for i in range (len(categories)):
print(str(i+1)+".", categories[i])
choice = int(input("Choose a category by typing the number beside the categories name."))-1
print("Items in this list are")
print("Itemname \t Price \t Stock")
final = location[choice]
for c in range((int(len(final)/3))):
print(str(c+1)+'.',str(final[c*3]),"\t",'$'+str(final[c*3+1])), "\t", str(final[(c*3)+2])
choice = int(input("Which item (Type number on left of the item name)"))-1
while True:
quanti = int(input("How many do you want to buy"))
if quanti > final[choice*3+2]:
print("Sorry your request for", quanti, "Is more than we have at the store please try again")
continue
else:
price = str(quanti*final[choice*3+1])
final[choice*3+2] = final[choice*3+2]-quanti
print("Thank you for your purchasing",quanti,"of", final[choice*3], "Your total price of this buy is", '$'+price)
for n in range (len(users)):
if usern == users[n].get("username"):
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f, "bought", quanti, "of", final[choice*3], "with a total price of $"+price)
order += str(quanti, 'of', final[choice*3])
price += int(price)
done = input("Do you want to check out then type '1' if you want to continue type '2'")
if done == '1':
print("Thank you")
print ("Invoice:", order, "/n total price (HKD) $"+str(price))
else:
coun += 1
menu(usern,names_f)
variable_name = users[n]["Transactions"] + str(names_f) + "bought" + str(quanti) + "of" + str(final[choice*3]) + "with a total price of $"+ str(price)
users[n]["Transactions"] = variable_name
You will maybe need to declare variable_name somewhere.
Problem is that str usage is following
str(object, encoding=encoding, errors=errors)
but whenever you pass comma it count it as another parameter.
P.S. I'm not sure if you need all those str in my solution.
str is a class, and as stated in the docs you can pass up to 3 parameters to it:
class str(object=b'', encoding='utf-8', errors='strict')
Also, it also says what it does:
Return a string version of object. If object is not provided, returns the empty string.
Meaning it is used to cast other types to string. Thus, you need to convert every int individually:
users[n]["Transactions"] = users[n]["Transactions"] + str(names_f) + " bought " + str(quanti) + " of " + str(final[choice*3]) + " with a total price of " + str(price)
Note the spaces before and after every string. Alternatively, you can format your string:
users[n]["Transactions"] = users[n]["Transactions"] + '%s bought %s of %s with a total price of %s' % (names_f, quanti, final[choice*3], price)
As a side note, it's worth checking what happens when the first transaction is made. If the key Transactions does not yet exist, you need to add an initial value before accessing it.
I usually do it like:
if key not in dict_:
dict_[key] = 'my initial value'
dict_[key] += 'add my stuff'
another solution would be using the get method, which allows you to add a default value:
dict_.get(key, 'default')
Note that this will not add the key to the dictionary, meaning that trying to access its value later on will still result in a Key Error.
playlistname = input("Input name of the playlist")
(playlistname) = ["1", "2", "3"]
search = input("Whats the name?")
if search == playlistname:
print(playlistname)
else:
print("Wrong")
When asked for the name of the playlist, if the user inputs the correct name of the list I want it to display the list, but instead it goes to the else statement. (Presumably because if search == playlist name means it is seeing if search is equal to the contents of the list).
If you could suggest a way to do this I would greatly appreciate it :)
Your question is not clear. But are you trying to do something as follows:
playlists = {'playlist1': ["1", "2", "3"], 'playlist2': ["4", "5", "6"],
'playlist3': ["7", "8", "9"]}
search = input("Whats the name?")
if search in playlists.keys():
print(playlists[search])
else:
print("Wrong")
If the user gives input as playlist2, the program will print [4, 5, 6].
playlistname = input("Name of PLaylist")
(playlistname) = ["blabla", "bla", "b"]
search = input("Whats the name?")
if search in playlistname:
print(search)
else:
print("Wrong")
This will print the playlist name if it finds that name in your list
villains = ["The Joker","Magneto","Red Mist","Doc Ock"]
for counter in range(4):
print (counter)