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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Dante
  • 59
  • 6

2 Answers2

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
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
  • 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. – Dante Feb 24 '20 at 04:44
  • 2
    if you are using python 2.7 just replace `input` with `raw_input` – Shubham Sharma Feb 24 '20 at 04:45
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
Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33
  • I still get 0.0 as my answer. I am using python 2.7 if that helps. – Dante Feb 24 '20 at 04:46
  • 1
    @Dante in python 2.7, use `raw_input` instead of `input` https://stackoverflow.com/questions/4960208/python-2-7-getting-user-input-and-manipulating-as-string-without-quotations – Hymns For Disco Feb 24 '20 at 04:58