Creating and Manipulating Variables in Python for Summation

In summary: In terminal, ', x except KeyboardInterrupt: # if the user presses Ctrl+C, the program will exit
  • #1
Couperin
59
0
I want to write a program like this. It asks for a number, n. It then creates n variables, for example variable_1, variable_2 ... variable_n. Then, after some more input, values are given to these variables.

I want to do this because at the end of the program, I want to my program to find the sum of those variables.

Any ideas how to do this?
 
Technology news on Phys.org
  • #2
I think I have an idea now actually.

Create a list for variables, eg

var_list = [v0, v1, v2, v3, v4]


Then ask for the amount of variables you want to use, eg

z = input('How many variables do you want?')
del var_list[z:5] # 5 is the amount of variables in the list, could be more depending on how big I make the list.
counter = 0


then

for ? in range z:
print 'Give me a value for variable', counter + 1
var_list[counter] = input('_ ') # assign that value to the number in a list
counter = counter+1


Then just find the sum of all the variables in the list (though I'm not sure how to do this.

I'll test this out, but it might not work. If it's obviously wrong, or if there's a better way of doing this, please share :).
 
Last edited:
  • #3
http://docs.python.org/tut/node7.html

What you are searching for is an array; though Python does not seem to refer to them as an array. Python refers to them as Lists. An array basically is a buffer of variables. Read through that document.
 
Last edited by a moderator:
  • #4
Thank you.
 
  • #5
Need more help! Okay I have this. When you run the program, it creates a list with z items. At the moment, it assigns each item on the list with the phrase 'HELP ME'. How could I utilise my count variable into the name of the item? What I mean is, how could I get my function to create a list such as 'HELP ME 0', 'HELP ME 0', 'HELP ME 0'?

Here's my code so far...

Code:
def setzonelist(z):
    count = 0
    while z > 0:
        zonelist.insert(count, 'HELP ME')
        count = count+1
        z = z - 1zonelist=[]
z = input('How many zones?_ ')
setzonelist(z)
print zonelist
 
Last edited:
  • #6
Here is an example:

Code:
def setzonelist(z):
        for count in range(z):
                zonelist.insert(count, 'HELP ME' + repr(count))


z = input('How many zones?_ ')

zonelist = []
setzonelist(z)

print zonelist

Noticed I implemented the for loop instead of the while.
 
  • #7
Thanks for your help mate. I didn't need to do the adding numbers thing in the end, but I've saved your code because I'm sure it'll come in handy soon. I've used your for loop idea though, much tidier :).

The reason for all this is that I came up with an idea for a simple resistance calculator when I woke up, and since I'm trying to learn a programming language I thought I'd use this opportunity to learn more!

I've almost finished the program I was making, but there's one last problem I'm having. Here's my code:

Code:
zonelist = []                               # list of overall resistance values for each zone
resilist = []                               # values of resistors in a single path
patvlist = []                               # each number is the sum of resistors in their path, with a zone

def inti(prompt):
    while 1:                                # loop infinitely
        x = raw_input('> ') # request a string
        try:
            new_x = int(x)                  # convert the input to a floater
            break                           # the conversion was successfull: break out of the loop
        except ValueError:                  # this block is accessed if the integer conversion fails
            print 'Please enter an integer. Not a string.'
    return new_x                            # return the floater

def pathos():
    global zonevalue
    counter1 = 0                                    # get totals for each path and then do appropriate calculations to get a total for the zone
    for count in range(appnum):                     # For each path in the current zone
        print 'How many resistors in path', counter1 + 1, '?'    
        resinum = inti('')                          # amount of resistors. used so that the values are asked for that amount of times
        counter1 = counter1+1
        counter2 = 0
        for count in range(resinum):                # plug in resistor values
            print 'What is the value of resistor', counter2 + 1, '?'
            appnumres = inti('')                    
            resilist.append(appnumres)              # put the number in a sequence
            counter2 = counter2 + 1
        seriesval = sum(resilist)                   # get the sum of the resistances on that path
        invseriesval = (1/seriesval)                # get reciprocal for parallel circuit
        print invseriesval
        if appnum > 1:                              # if the zone has parallel paths, use reciprocal
            patvlist.append(invseriesval)
        else:                                       # if the zone is a series, ie it has one path, just use the sum
            patvlist.append(seriesval)
    sum_of_all_paths = sum(patvlist)                # add up the sum of the paths
    if appnum > 1:                                  # if parallel, get the reciprocal
        zonevalue = sum_of_all_paths**-1
    else:                                           # otherwise just return the series value (coulda done this tidier...)
        zonevalue = seriesvalprint 'How many zones in the circuit?'
z = inti('')                                # number of zones in circuit. used to dictate number of loop that asks for amount of paths in each zone
counter = 0                                 # sets up counter
for x in range(z):
    print 'How many paths in zone', counter + 1, '?'
    appnum = inti('')                       # asks for amount of paths, so that the pathos loop can be run a sufficient amount of times
    pathos()
    zonelist.append(zonevalue)
    counter = counter + 1

total_resistance = sum(zonelist)
print 'The total resistance in the circuit is', total_resistance, 'ohms.'

As you can see, I've put in something that let's you just work out series resistances. But parallel resistances require floating point number for the calculations to work. At the moment, 1/n seems to want to = 0, which isn't very helpful when it comes to finding the reciprocal of all those 0s :D.

At the beginning of the program I've used a function that 'Sane' from this forum made, that forces you to input numbers instead of strings. At the moment it only takes integers. I tried changing the 'int' to 'float' in the function, but it didn't work. My python claimed that it expected an int... a bit presumptious of python, lol :D.

Anyways, I'd like to know how to get it so that this program can use floating points instead of integers.

Thanks!
 
  • #8
Welcome. Later I shall look at the code. I must leave and am not returning until tonight.
 
  • #9
Couperin said:
1/n seems to want to = 0

Try "1.0/n".
 
  • #10
Cheers mate, that worked a treat.

The code I posted above doesn't work, but I've changed it and I now have a fully functioning program (albeit one that no one would ever want to use, lol :D).

Thanks arevolutionist and nmtim for your help.
 

1. What is a variable in Python?

A variable in Python is a name given to a specific value or data type that can be stored and manipulated by the computer. It acts as a placeholder for data and allows us to refer to that data by using the variable name instead of the actual value.

2. How do you create a variable in Python?

To create a variable in Python, you simply need to use the assignment operator "=" and provide a variable name followed by the desired value or data type. For example, to create a variable called "age" and assign it a value of 25, you would write "age = 25".

3. Can variables be reassigned in Python?

Yes, variables in Python can be reassigned to store a different value or data type. This means that the same variable name can be used to store different data at different points in the program. For example, you can assign "age = 25" and later reassign it to "age = 30".

4. What are the naming conventions for variables in Python?

Variables in Python can be named using letters, numbers, and underscores. They cannot begin with a number and are case sensitive, meaning "age" and "Age" are two different variables. It is recommended to use descriptive names that are easy to understand and follow a consistent naming convention.

5. How do you delete a variable in Python?

To delete a variable in Python, you can use the "del" keyword followed by the variable name. This will remove the variable and its associated value from the program's memory. It is important to note that once a variable is deleted, it cannot be recovered.

Similar threads

  • Programming and Computer Science
Replies
7
Views
463
  • Programming and Computer Science
Replies
10
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
1
Views
273
  • Programming and Computer Science
Replies
3
Views
312
  • Programming and Computer Science
Replies
1
Views
740
  • Programming and Computer Science
Replies
1
Views
982
  • Programming and Computer Science
Replies
1
Views
1K
Back
Top