pythonjes

adding and variable assignment in Python


def sumOfStudentDigits():  
    studentdigit = (studentdigit1 + studentdigit2 + studentdigit3 + studentdigit4 + studentdigit5 + studentdigit6 + studentdigit7)

    studentdigit1=3 studentdigit2=6 studentdigit3=9 studentdigit4=3 
           studentdigit5=1 studentdigit6=0 studentdigit7=0

I need to assign seven digits to seven variables and add them together.


Solution

  • If your confusion is how to get the studentdigits into your function, you can pass them into the function like this:

    def sumOfStudentDigits(studentdigit1, studentdigit2, studentdigit3,
                           studentdigit4, studentdigit5, studentdigit6,
                           studentdigit7):
        studentdigit = (studentdigit1
                        + studentdigit2
                        + studentdigit3
                        + studentdigit4
                        + studentdigit5
                        + studentdigit6
                        + studentdigit7)
    

    My advice would be to have all those digits stored in a list, and then pass merely that list to the function, then iterate over the list:

    listofdigits = [studentdigit1,
                    studentdigit2,
                    studentdigit3,
                    studentdigit4,
                    studentdigit5,
                    studentdigit6,
                    studentdigit7]
    
    def sumOfStudentDigits(studentdigitlist):
        sum = 0
        for digit in studentdigitlist:
            sum += digit
            return sum
    
    print(sumOfStudentDigits(listofdigits))
    

    We have to set sum = 0 before we can use sum because python wants to know what sum is before it uses it, so we assign it 0 so that we can count up from there. Notice how studentdigitlist and listofdigits are different? You can pass a list of any name to the function, all that matters is that you use the variable (ie a list in this case) name that you have used in def myfunction(yourvariable): throughout the function definition. Python with substitute whatever you pass into the function for where you have that placeholder name within the function. Then when you run the function: eg

    def myfunction(yourvariable):
        # do stuff with yourvariable
        myvariable = myvariable + 7
    
    somenumber = 2
    myfunction(somenumber)
    # now somenumber will equal 9