user1316212
user1316212

Reputation: 21

How can I make an float have a specific range in python 3 (or can I at all)?

I have been trying to get this program to work, and it runs but once I got it to run I uncovered this problem. Right now it asks for gradePoint and credit hours and prints out a GPA like it is supposed to, but I can type anything in gradePoint and it will spit out a value. What I want is gradePoint to only work if the user types in a number between 0.0-4.0. I was thinking of a loop of some sort, like an if loop but is there an easier way (or a preferred way) to do this?

Here's the code:

def stu():
stu = Student

class Student:
def __init__(self, name, hours, qpoints):
    self.name = name
    self.hours = float(hours)
    self.qpoints = float(qpoints)

def getName(self):
    return self.name

def getHours(self):
    return self.hours

def getQpoints(self):
    return self.qpoints

def getStudent(infoStr):
    name, hours, qpoints = infoStr.split("\t")
    return Student(name, hours, qpoints)

def addGrade(self, gradePoint, credits):
    self.qpoints = gradePoint * credits
    self.hours = credits
    self.gradePoint = float(gradePoint)
    self.credits = float(credits)

def gpa(self):
    return self.qpoints/self.hours

def main():
stu = Student(" ", 0.0, 0.0)
credits = int(input("Enter Credit Hours "))
gradePoint = float(input("Enter Grade Point"))
if gradePoint > 4.0:
        print("Please enter a Grade Point that is less then 4.")
stu.addGrade(gradePoint,credits)
output = stu.gpa()
print("\nStudent GPA is: ", output)


main()

This is the shell printout(I know the grade point is repeated in the GPA, this is for a class and we were supposed to use a skeleton program and change some things):

Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is:  3.5

Enter Credit Hours 12
Enter Grade Point 3.2
Student GPA is:  3.2

Thanks!

EDIT: I just did an if loop as suggested in the comments and it worked somewhat in that it printed out what I wanted but didn't make it stop and wait for the correct input. I'm not exactly sure how to get it to do that.

Here is the new print from the shell:

Enter Credit Hours 4
Enter Grade Point 3.5
Student GPA is:  3.5

Enter Credit Hours 4
Enter Grade Point 4.5
Please enter a Grade Point that is less then 4.
Student GPA is:  4.5

Upvotes: 1

Views: 385

Answers (2)

Luc125
Luc125

Reputation: 5837

You can check if user input meet your requirements and throw an exception if not. This will make the program log an error message and stop on invalid user input.

The most basic way to do this is to use an assert statement:

def main():
    stu = Student(" ", 0.0, 0.0)
    credits = int(input("Enter Credit Hours "))
    assert credits > 0 and credits < 4, "Please enter a number of Credit Hours between 0 and 4."

If you wish the application to keep prompting the user until a valid input is entered, you will need at least one while loop.

For exemple:

def main():
    stu = Student(" ", 0.0, 0.0)
    while True:
        credits = int(input("Enter Credit Hours "))
        if credits > 0 and credits < 4:
            break
        else:
            print("Please enter a number of Credit Hours between 0 and 4")

    while True:
        gradePoint = float(input("Enter Grade Point"))
        if gradePoint <= 4.0:
            break
        else:
            print("Please enter a Grade Point that is less then 4.")

    stu.addGrade(gradePoint,credits)
    output = stu.gpa()
    print("\nStudent GPA is: ", output)

Upvotes: 1

Joel Cornett
Joel Cornett

Reputation: 24788

Create a function that gathers a valid float from the user within a range:

def getValidFloat(prompt, error_prompt, minVal, maxVal):
    while True:
        userInput = raw_input(prompt)
        try:
            userInput = float(userInput)
            if minVal <= userInput <= maxVal:
                return userInput
            else: raise ValueError
        except ValueError:
            print error_prompt

And then use like this:

gpa = getValidFloat(
    "Enter Grade Point ",
    "You must enter a valid number between 1.0 and 4.0",
    1,
    4)

The output would look something like this:

Enter Grade Point 6.3
You must enter a valid number between 1.0 and 4.0
Enter Grade Point 3.8

Upvotes: 0

Related Questions