1

I need to take an input in the following form "score/max" (Example 93/100) and store it as a float variable. The problem I run into is that python does the division indicated by backslash and since the two numbers are integers, the result is 0. Even if I convert my input into a float the result is 0.0. Here is my code for reference:

#!/usr/bin/env python

exam1=float(input("Input the first test score in the form score/max:"))

If 93/100 is entered, exam1 variable will be equal to 0.0 instead of the intended 0.93.

2
  • Keep in mind that you need to handle the 'Divide by zero error' Commented Feb 24, 2020 at 4:33
  • 93/100 is not a float. It you calculate its result then it can be interpreted as a float. Commented Feb 24, 2020 at 4:36

2 Answers 2

2

Note:

input()

reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

You may want to try the following code,

string = input("Input the first test score in the form score/max: ")
scores = string.strip().split("/")
exam1 = float(scores[0]) / float(scores[1])

print(exam1)

Input:

Input the first test score in the form score/max: 93/100

Output:

0.93
Sign up to request clarification or add additional context in comments.

2 Comments

The code you have provided does not work. The error that I get is the following: AttributeError: 'int' object has no attribute 'strip' I am using python 2.7 if that helps.
if you are using python 2.7 just replace input with raw_input
1

You could use python's fractions module, which knows how to read a fraction string

from fractions import Fraction
exam1 = float(Fraction(input("Input the first test score in the form score/max:")))

for Python 2.7, use raw_input instead of input

see Python 2.7 getting user input and manipulating as string without quotations

Input the first test score in the form score/max:93/100
>>> exam1
0.93

2 Comments

I still get 0.0 as my answer. I am using python 2.7 if that helps.
@Dante in python 2.7, use raw_input instead of input stackoverflow.com/questions/4960208/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.