Home > Enterprise >  I've declared variable "x" but i did not call it, is it ok to not call variables that
I've declared variable "x" but i did not call it, is it ok to not call variables that

Time:12-05

import random


def add_sums(Num):
    total = 0
    all_num = []
    for x in range(1, Num 1):
        gen = random.randint(1, 30)
        all_num.append(gen)
    
    print("List:", all_num)
    for y in all_num:
        total  = y
    print("List total:", total)


user_max = int(input("Max numbers in list: "))
add_sums(user_max)

In this program, the user will enter the total amount of numbers in a list. the random module will generate random numbers between 1 to 30. Then all the numbers from the list will be added together.

I've tried to use the variable x but it doesn't give the results I want, does anyone know a better/simpler way of creating this program. Also, is it bad practice to create a variable and not call it?

CodePudding user response:

Maybe this better/simpler way of creating this program

import random

def add_sums(Num):

    all_num = []
    for x in range(Num):
        all_num.append(random.randint(1, 30))
    print("List:", all_num)
    print("List total:", sum(all_num))
user_max = int(input("Max numbers in list: "))

add_sums(user_max)

CodePudding user response:

When you're iterating through a list but don't need the index, it's common to use an underscore to indicate the index isn't used.

for _ in range(1, Num 1):
    gen = random.randint(1, 30)
    all_num.append(gen)
  • Related