Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for Using function to minimize the amount of code

$
0
0

The reason you need so much code is due to the way you're storing the information — namely differently named variables for each one — requires writing code specific to each one of them. To truly minimize the code need to solve the problem (for any number of students) is to store the data in a different manner — which will make it relatively easy to write a generic function for entering the information for any one of them.

In the code below the info for each student is stored in a list of instances of a "dataclass" named Student which can easily be defined using Python's dataclasses module — a utility to make structured classes specially for storing data which was added in version 3.7 (see PEP 557).

Once that's done, then writing a function like you want (get_student_info() in the code below) is a relatively simple matter because all it has to do is gather three pieces of information and pass them back to the caller.

from dataclasses import dataclass@dataclassclass Student:"""Class for keeping track of student's favorite number and gender."""    name: str    favorite: int    gender: strdef get_student_info():"""Prompt user for pieces of information needed to create an instance of the    Student class and return it as a tuple."""    name = input("Please enter student's name or just the Enter key to quit: ")    if not name:        return None  # Terminate data entry.    while True:        try:            favorite = int(input('Please enter their favorite number between 1 and 100: '))        except ValueError:            print('sorry, that is not a valid integer')            continue        if 1 <= favorite <= 100:            break        else:            print('Number is not in range of 1 to 100, please try again')            continue    while True:        gender = input('Please enter their gender identity ("boy" or "girl"): ')        if gender in ("boy", "girl"):            break        else:            print('Sorry, that is not an acceptable gender identity, please try again')    return name, favorite, gender# Create a list of Students.students = list()print('Enter student information for list\n')while True:    info = get_student_info()    print()    if not info:        break    students.append(Student(*info))print()print('Student list created:')for i, student in enumerate(students, start=1):    print(f'{i}: {student}')

Sample usage:

Enter student information for listPlease enter student's name or just the Enter key to quit: JohnPlease enter their favorite number between 1 and 100: 1Please enter their gender identity ("boy" or "girl"): boyPlease enter student's name or just the Enter key to quit: MarkPlease enter their favorite number between 1 and 100: 50Please enter their gender identity ("boy" or "girl"): boyPlease enter student's name or just the Enter key to quit:Student list created:1: Student(name='John', favorite=1, gender='boy')2: Student(name='Mark', favorite=50, gender='boy')Press any key to continue . . .

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>