Dan
Dan

Reputation: 157

Quiz point variable python

So I'm currently creating a basic python code as I am kinda new. Here is my code:

import sys

points = 0
Start=input("Press Enter to start the quiz or type quit to end exit: ")
if Start == "quit":
    sys.exit()
elif Start == "":\
    print("Hello, Welcome to the maths quiz!" + "\n" "You will be asked 10 questions in total. - For every correct answer you will gain one point" + "\n" "For every wrong answer, one point wil be deducted from your total points" + "\n")
else:
    sys.exit()

firstq=input("First answer: What is 10+10?: ")
if firstq == "20":
    points = points + 1
    print("Correct answer! Total points:" + str(points))
else:
    points = points - 1
    print("Wrong answer! Total points:" + str(points))

If the answer was wrong on the first question. Points would be -1. However, is there a way that it doens't make points a negative but rather stay at 0? Would I have to create another if statement which would like look this:

firstq=input("First answer: What is 10+10?: ")
if firstq == "20":
    points = points + 1
    print("Correct answer! Total points:" + str(points))
else:
    if points > 0:
        points = points - 1
    print("Wrong answer! Total points:" + str(points))

Or is there a better way of doing this because I would have to add this for every question:

if points > 0:
        points = points - 1

Upvotes: 0

Views: 278

Answers (3)

blhsing
blhsing

Reputation: 106543

You can make use of the truthy value and only assign points - 1 to points when it is truthy, which in your case happens only when points is greater than 0:

points = points and points - 1

Upvotes: 0

Kvothe
Kvothe

Reputation: 128

You can define a function for that. Write above the other code

def calculate_points(new_points, current_points):
    current_points += new_points
    if current_points < 0:
        return 0
    else:
        return current_points

call it in your code:

# instead of points = points + 1
points = calculate_points(1, points)

# instead of points = points -1 . Your points will never be under 0
points = calculate_points(-1, points)

Upvotes: 0

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8039

Probably the most straightforward way is the following:

points = max(points - 1, 0)

so points wouldn't be decremented when the next value is less than 0.

A couple of other options:

1) Ternary if

points = points - 1 if points > 0 else 0 

2) Custom class and magic method in case if you need more complex scoring logic in other places.

class Score: def init(self, start_val=0): self.points = start_val

def increment(self, val=1):
    self.points += val

def decrement(self, val=1):
    self.points -= val

Upvotes: 2

Related Questions