This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I want to change the value of a variable that's inside another variable, this is the code I have so far:
person1tokens = 0
person2tokens = 0
token_price = 5
accounts = ["person1tokens","person2tokens"]
def add_tokens(person,amount):
if person in accounts:
cost = amount*token_price
print("You need to pay %d$" % (cost))
payment = int(input("Payment? "))
if payment != cost:
print("Please enter the right amount next time, nothing changed")
else:
--Help here--, change value of a the in the function specified account to <account> += amount
print("Added " + str(amount) + " tokens to account " + str(person) + ", your current balance is " + str(eval(person)"."))
else:
print("fail")
I basically want to change the value of person1tokens(for example) without knowing beforehand that I want to change that value, and I want to change that value where it says --Help here--.
But the problem is that it is inside the person variable and I don't know how to get the program to "unpack" it from there.
So for example if the user does as follows:
add_tokens("person1tokens",5)
You need to pay 25$
Payment? 25
Added 25 tokens to account person1tokens, your current balance is 25.
Any ideas?
If I'm understanding you correctly here, you want to be able to change the value of either person1tokens or person2tokens without knowing which will be changed beforehand (please correct me if I'm wrong). One way I can think to do this would be using a dictionary rather than storing their values in their own separate variables, and then changing the values based off of that.
accounts = {'person1tokens': 0,
'person2tokens': 0}
def add_tokens(person, amount):
if person in accounts:
cost = amount*5
payment = int(input("Payment? "))
if payment != cost:
print("Please enter the right amount next time, nothing changed")
else:
accounts[person] = accounts[person] + cost
print("Added " + str(amount) + " tokens to account " + str(person) + ", your current balance is " + str(accounts[person]) + ".")
else:
return False
This would allow you to have a large amount of people and simply refer to them by name. The one downside to this for you is that you won't be able to refer to the variables, but you can still reference the persons balance by doing accounts['nameofperson']
Hope this helped!
Related
This question already has answers here:
Replacements for switch statement in Python?
(44 answers)
Closed 2 years ago.
I'm building a currency converter and I've pretty much finished the program. However, I am trying to eliminate redundancy by implementing a function or a define block. I've tried a number of things but it does not seem to be working.
My current code is like this:
EUR = 0.83
EGY = 16.22
def currency_converter():
money = total_value
new_value = 0
if currency == 1:
new_value = money*EUR_CON
print("Your total is " + "$" + str(money) + " US Dollars which is " + "e£ " + str(new_value) + " European Euros.")
elif currency == 2:
new_value = money*EGY_CON
print("Your total is " + "$" + str(money) + " US Dollars which is " + "e£ " + str(new_value) + " Egyptian Pounds.")
I want to essentially make the clause under the if/elif block a function. I've tried doing this:
def conversion(EUR_CON,GDP_CON, BRL_CON, EGY_CON, YEN_CON):
new_value = money*conversion()
print("Your total is " + "$" + str(money) + " US Dollars which is " + str(new_value)+ str(conversion)
if currency == 1:
conversion(EURO_CON)
But it's not working. Can someone help?
The correct way to do this is to make a mapping or enum that ties the type of conversion to the associated parameters (in this case, the multiplier and the string name of the target currency). For example, with enum:
from enum import Enum
class Currency(Enum):
EUR = 0.83, "European Euros"
EGY = 16.22, "Egyptian Pounds"
def currency_converter(target_currency):
multiplier, name = target_currency.value # Retrieve value of enum and unpack parts for use
new_value = money * multiplier
print(f"Your total is ${money} US Dollars which is {new_value} {name}")
which then allows you to use it with just:
currency_converter(Currency.EUR) # Convert to euros
To be clear: Using a dict for a similar purpose is perfectly fine as well. Enums mostly just emphasize that there are a fixed, known set of possible conversions, where dicts don't have that idea baked in as thoroughly (adding and removing keys is always a possibility).
I'll note that in real code, functions generally shouldn't rely on receiving non-constant information from globals, nor should they print the results (returning them allows the caller to print, or not print, as they choose) so a better design would be something like:
def convert_usd_to_currency(target_currency, money):
multiplier, _ = target_currency.value # Retrieve value of enum and unpack parts for use
return money * multiplier
possibly with a helper that does the printing (if you really have many places that need to format it the same way):
def print_converted_currency(currency, money):
new_value = convert_usd_to_currency(currency, money)
print(f"Your total is ${money} US Dollars which is {new_value} {currency.name}")
I'll admit to a failure of imagination here; I almost never see a need to factor out the output code itself (each location prints different things based on need), so I'd probably just inline that work in the one place that actually prints it (as opposed to potentially many places that need to perform the conversion).
Put all your conversion rates into a list or dictionary, so you don't need all those if statements.
You don't need so many parameters to the function. Just the currency you're converting to and the amount. The function can then look up all the information related to the currency parameter.
conversion_data = {
'EUR': {'rate': 0.83, 'symbol': '€', 'name': 'European Euros'},
'EGY': {'rate': 16.22, 'symbol': '£', 'name': 'Egyptian Pounds'},
...
}
def conversion(currency, dollars):
new_value = dollars * conversion_data[currency]['rate']
return f"Your total is ${dollars} US dollars which is {conversion_data[currency]['symbol']}{new_value} {conversion_data[currency]['name']}."
print(conversion('EUR', 5))
I am trying to write a program that takes two values, same and add, and generates a total value of both, a spend value (80% of the sum,) and a save value (20% of the sum.) The purpose is so that I can input a certain amount of money as my same (the amount of money I had before), and everytime I receive more money, I can call the function, put the new amount of money in as the add value (the money I just gained), and skip having to count all the money and calculate a save and spend myself. The problem is I don't know how I can use the new total I calculated the next time I call the function without having to count the money and use that as the new same value the next time, which defeats the purpose of the whole program.
def eightovertwo(same,add): # takes two values, adds them, then gives an 80% and 20% value
if same == 'none' or same == 'nil':
print ("") # ?
total = float(same + add)
print ("Your total is:" + " " + str(total))
total /= 10
spend = total
save = total
spend *= 8
save *= 2
print ("Your spend is:" + " " + str(spend))
print ("Your save is:" + " " + str(save))
eightovertwo(0, 25)
I made a Python program to repeat the number of internships that I applied for, BUT I need it to store the amount I add so that I can ask it later how many I applied for, rather than me having to enter a number every time. Also, I want it to be able to update if the number of internships I applied for changes, I will input the new number of internships manually. How can I change my program to do that? Please take a look thanks
print("Welcome back, Ryan")
internships = {}
asking_ryan = True
amount = input("Enter how many internships you have applied for: ")
amount = int(amount)
if amount > 1:
print("You have applied for: " + str(amount) + " internship(s)")
str(amount)
if amount < 1:
print("Error! you cannot apply for 0 internships!")
if amount == 1:
print("You have applied for: " + str(amount) + " internship")
Program output:
Welcome back, Ryan.
Enter how many internships you have applied for: 2
You have applied for: 2 internship(s)
I saw your question. I kind of understand it.
You want to be able to update the internships you have done so you don't have to always rerun the program so it counts your internship?
You might have to use some files for that, should be simple!
First, you can make a file called opens.txt and add a 0 to the file that tracks how many times you opened that program. When you run the program do this:
opens = open("opens.txt", w+)
open_count = int(opens.read())
opens.write(open_count + 1)
if open_count == 1:
amount = input("Enter how many internships you have applied for: ")
... # Other Code
Then make a file called something like internships.txt where it will store how many internships you currently have, default it to 0.
internships = open("internships.txt", w+)
internship_count = int(internships.read())
print("You currently have applied to {} internships since last time...".format(internship_count)
new_internships = input("How many new internships have you applied for? ")
internships.write(internship_count + new_internships)
I think this should help? Haven't used files in a long time. Next time please phrase your question a bit better.
This question already has answers here:
TypeError: not all arguments converted during string formatting python
(9 answers)
Closed 3 years ago.
I am new to python and programming in general, I am currently using codecademy to learn this course, however I have tried to expand on abit of what i know from the course and develop little ideas I have, to help me understand better. However when ever get to this part of the code, it gives me this error.
File "TeamSelector.py", line 12, in <module>
print ("\n You have been asigned to team number: " + str(teamSelection % teams))
TypeError: not all arguments converted during string formatting
PS C:\users\worri\documents\development\python>
Here is my full code
import sys
testInt = 64
teams = input("\n How many teams are there? \n")
print ("There are " + teams + " number of teams.")
totalPlayers = input ("\n How many total players are there \n")
print ("There are " + totalPlayers + " players to be selected into teams.")
teamSelection = input ("\n What is your assigned number? \n")
print ("\n You have been asigned to team number: " + str(teamSelection % teams))
I have tried many things, even having a seperate variable to do the calculation to pass it as part of the string at the end, i have looked on google for different ways and whatever I have tried it gives the same error. I understand enough that I think the typeError is having problems passing the float/int to a string, but i cant seem to find a .toString() feature, that I have used before when I tried to learn java. If anyone can help me i would be most grateful. Thank you.
This error is due to the fact that your teamSelection and teams variables must be converted to integers before taking the modulus (the modulus operator works on numbers, not strings). When you use the input() function, your input is read as a string.
This can be fixed by changing the last line of code with the following:
team_assignment = int(teamSelection) % int(teams)
print("\n You have been asigned to team number: " + str(team_assignment))
Always use snake_case to name your variables. Please refer to this article
teams = input("How many teams are there? \n")
print("There are " + teams + " number of teams.")
total_players = input("How many total players are there \n")
print("There are " + total_players + " players to be selected into teams.")
team_selection = input("What is your assigned number? \n")
print("You have been assigned to team number: " + str(int(team_selection) % int(teams)))
or else
print(f"You have been assigned to team number: {str(int(team_selection) % int(teams))}")
I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")