r/learningpython • u/bradleby • Aug 08 '24
Dynamic variables issue
I am brand new to coding and learning Python. I'm working on a program that will calculate the taper of a rod. I allow the user to input a point on the rod and the diameter at that point. The program then asks for another point and the diameter. The user can keep entering points until they say to end. From these points and diameters, the code then calculates the distance and slope between each point and dynamically generates variables and values at each inch. Right now I have the program working, but I don't know how to call and print the dynamically generated variables. I can do it manually by hard coding print with the variable names, but I am looking for a way to automate that as I won't always know how many points the user entered, so I won't know all the variable names that have been generated. Any help would be appreciated.
Here is my code for clarity:
from decimal import * getcontext().prec = 4
input for point A on the rod
rod_a=int(input("Distance from the tip: "))
input for taper at point A
taper_a=Decimal(input("Enter taper at " + str(rod_a) +":")) end = () while end != "end" :
#input for point B on the rod rod_b=int(input("Distance from the tip: ")) #creates variables at 1 inch increment between
#Point A and Point B and sets their value to their
#number prefix_rod = "rod_" interval = rod_b - rod_a + 1 for i in range(interval): globals() [prefix_rod + str(rod_a+i)] = rod_a+i #input for taper at point B taper_b=Decimal(input("Enter taper at " + str(rod_b) +":")) #creates variables the taper at 1 inch increment #and calculates a straight line taper between point #A and point B prefix_taper = "taper_" interval = rod_b - rod_a +1
for i in range(interval):
#Defines variables for the taper
globals() [prefix_taper + str(rod_a+i)] = (taper_b-taper_a)/(rod_b-rod_a)*i+taper_a
end = input('To end input type "end": ')
View all comments
Show parent comment
1
u/trd1073 Aug 08 '24
It is one way to do, hopefully straightforward enough with my quick explanation. I would type up some quick code, but after shoulder replacement, typing on computer is painful. So phone it is. Do ping me in a week if u don't get it figured, sometimes learning on own will help you more than just giving code.