Home > Software design >  How to randomly generate numbers each time the program is run and store those values in a list?
How to randomly generate numbers each time the program is run and store those values in a list?

Time:10-25

I am writing a program that asks the user to input a list of students. Once the list is made the user can input a student's name that was listed before to show 4 random integers from 1 to 100 that represent 4 different marks on assignments. When I run this program, however, the mark is the same number each time. How do I run the program so that each number for the mark is different, also how can I store these values in a separate list? Thank You!

def printMark(studentMark, studentName):
    print("Enter the names of your students")
    print("Press the enter key to store another name. print q or Q when you're done.")
    names = input("Enter student name: \n")
    classlist = []

    while True:
        names = input("")
        if str.lower(names) == 'q':
            break
        classlist.append(names)

    for name in classlist:
        print(name)

    student_choice = input("Enter a students in your classlist: ")
    if student_choice not in classlist:
        print("That students is not in your class")
    elif student_choice in classlist:
        mark = list(range(1, 101))
        print("A1:"   str(studentMark)   "\nA2:"   str(studentMark)   "\nA3:"   str(studentMark)   "\nA4:"   str(studentMark))

classlist = []
import random
mark = list(range(1, 101))
printMark(random.sample(mark, k=4), classlist)

CodePudding user response:

It seems like the error is in print("A1:" str(studentMark) "\nA2:" str(studentMark) "\nA3:" str(studentMark) "\nA4:" str(studentMark)).

If studentMark is a list, which is what I gather from my last moment research on random.sample, it seems like the problem is that you are using the same value each time rather than different list elements from studentMark. (Note that I'm assuming the random.sample technique would work like mark = [random.randint(1, 101) for _ in range(4)], but without repeated values.)

Instead maybe use:

print("A1:"   str(studentMark[0])   "\nA2:"   str(studentMark[1])   "\nA3:"   str(studentMark[2])   "\nA4:"   str(studentMark[3]))

You could also use:

print(*[f"A{i 1}: {mark}" for i, mark in enumerate(studentMark)])

This would simplify things but is more complicated than the original idea.

CodePudding user response:

Your printMark function shouldn't take a studentMark argument if the intent is for it to generate a different set of marks each time. It also shouldn't take a studentName argument since it doesn't use it. You could very easily write this script without any functions at all, and it'd be more straightfoward:

import random

print("Enter the names of your students")
print("Press the enter key to store another name. print q or Q when you're done.")
classlist = []
while True:
    names = input()
    if str.lower(names) == 'q':
        break
    classlist.append(names)
print(*classlist, sep='\n')

student_choice = input("Enter a students in your classlist: ")
if student_choice not in classlist:
    print("That student is not in your class")
else:
    for a in range(1, 5):
        print(f"A{a}:", random.sample(range(1, 101), k=4))

If you were going to use functions in this script, I'd suggest having one function to enter the class list and another to print a chosen set of marks given a class list:

import random

def get_class_list() -> list[str]:
    print("Enter the names of your students")
    print(
        "Press the enter key to store another name.  "
        "Enter q or Q when you're done."
    )
    classlist = []
    while True:
        name = input()
        if str.lower(name) == 'q':
            return classlist
        classlist.append(name)

def print_mark(classlist: list[str]) -> None:
    student_choice = input("Enter a student in your classlist: ")
    if student_choice not in classlist:
        print("That student is not in your class")
        return
    for i in range(1, 5):
        print(f"A{i}:", random.sample(range(1, 101), k=4))

print_mark(get_class_list())

CodePudding user response:

Hi firstly 2 questions 1: why you put this program inside a def it just makes it more complicated 2: if the students mark are random why you are taking them as a argument to the def? any ways here is the solution i came up with

def printMark(studentName):
    print("Enter the names of your students")
    print("Press the enter key to store another name. print q or Q when you're done.")
    names = input("Enter student name: \n")
    classlist = []

    while True:
        names = input("")
        if str.lower(names) == 'q':
            break
        classlist.append(names)

    for name in classlist:
        print(name)

    student_choice = input("Enter a students in your classlist: ")
    if student_choice not in classlist:
        print("That students is not in your class")
    elif student_choice in classlist:
        mark = list(range(1, 101))
        print("A1:"   str(random.sample(mark, k=4))   "\nA2:"   str(random.sample(mark, k=4))   "\nA3:"   str(random.sample(mark, k=4))   "\nA4:"   str(random.sample(mark, k=4)))

classlist = []
import random
mark = list(range(1, 101))
printMark(classlist)

Here: instead of taking student marks a argument i generated them when they are printed this way it generates every time it prints one previously it was taking one random mark and using it 4 times now its all different.

CodePudding user response:

Jhon, looks like your code was really close. I've made one edit:

def printMark(studentMark, studentName):
    print("Enter the names of your students")
    print("Press the enter key to store another name. print q or Q when you're done.")
    names = input("Enter student name: \n")
    classlist = []

    while True:
        names = input("")
        if str.lower(names) == 'q':
            break
        classlist.append(names)

    for name in classlist:
        print(name)

    student_choice = input("Enter a students in your classlist: ")
    if student_choice not in classlist:
        print("That students is not in your class")
    elif student_choice in classlist:
        mark = list(range(1, 101))
        print("A1:"   str(studentMark[0])   "\nA2:"   str(studentMark[1])   "\nA3:"   str(studentMark[2])   "\nA4:"   str(studentMark[3]))

classlist = []
import random
mark = list(range(1, 101))
printMark(random.sample(mark, k=4), classlist)

Here's a sample run:

Enter the names of your students
Press the enter key to store another name. print q or Q when you're done.
Enter student name: 
a
b
c
q
b
c
Enter a students in your classlist: b
A1:7
A2:93
A3:63
A4:86

CodePudding user response:

You should probably store the students in a dictionary when you want to bind their name to a list of their marks. Here is the solution I came up with:

import random

students = {}

while True:
    names = input("")
    if names.lower() == 'q':
        break

    # this is list comprehension, you can write 4 times random.randint(1, 100) as well
    students[names] = [random.randint(1, 100) for _ in range(4)]


student_choice = input("Enter a student from your list: ")
if student_choice not in students.keys():
    print("This student is not in your list.")
else:
    print(f"{student_choice}:\n"
          f"A1: {students[student_choice][0]}\n"
          f"A2: {students[student_choice][1]}\n"
          f"A3: {students[student_choice][2]}\n"
          f"A4: {students[student_choice][3]}")

It generates a list of 4 integers with random values every time a new user is added to the dictionary. This means that you can access the student's marks later in the code - unlike your solution, where you only decided what the student's mark was while printing it.

  • Related