Kind of a silly question for a def function Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Kind of a silly question for a def function Python

trying to get this def function to work for a string. without the def function the code works just fine ( yes I am sure it is not best practice and better ways to do it). def computegrade (score = float(input("Enter Score: "))): try: if score > 0.9 <= 1.0: print("A") elif score >= 0.8: print("B") elif score >= 0.7: print("C") elif score >= 0.6: print("D") elif score < 0.6: print("F") except: print('Please Enter Number') computegrade()

13th Oct 2017, 7:05 PM
Aric Dunn
Aric Dunn - avatar
6 Answers
+ 1
Works fine for me, seems like you have something wrong in your libraries or you messed up something that... 'shouldn't be messed with' I guess? I dunno... Unless you hard code the two " " literals, that introduces errors, if you do so (from a file or whatever, idk) try removing them first using regex and then introduce the params again. EDIT: Unless you code the input() part inside the function, instead of as a default argument. Then use a separate function and loop it with try/catch until you have a valid input... Idk just thoughts
13th Oct 2017, 7:32 PM
Muhammad Kamal
Muhammad Kamal - avatar
+ 1
input() returns a string object, so this is what works.. However taking the string from another source that enforces the two quotation marks, won't work straight away. I input for example a, 2 or 4.5 and all these work.
14th Oct 2017, 1:01 PM
Muhammad Kamal
Muhammad Kamal - avatar
0
Same thing with this code... need to prompt user if they enter other than a number.. works fine until I add def. my instructions say to take two "parameters" def computepay(hrs = float(input('Enter Hours: ')),rate = float(input('Enter Rate: '))): try: #hrs = float(input('Enter Hours: ')) #rate = float(input('Enter Rate: ')) if hrs <= 40: pay = (hrs * rate) print('Pay',pay) else: if hrs > 40: othrs = hrs - 40 print('Standard Pay:',(hrs - othrs) * rate ) print('Overtime Pay:', othrs * (1.5 * rate)) print('Total Pay:', ((hrs - othrs) * rate) + othrs * (1.5 * rate)) except: print('Please Enter Numbers: ') computepay()
13th Oct 2017, 7:07 PM
Aric Dunn
Aric Dunn - avatar
0
I get this... Enter Hours: xgbdf Traceback (most recent call last): File "C:/Users/aricd/PycharmProjects/Coursera/Coursera2.py", line 1, in <module> def computepay(hrs = float(input('Enter Hours: ')),rate = float(input('Enter Rate: '))): ValueError: could not convert string to float: 'xgbdf' Process finished with exit code 1
13th Oct 2017, 7:08 PM
Aric Dunn
Aric Dunn - avatar
0
So you were able to type a string and it worked ?
13th Oct 2017, 7:36 PM
Aric Dunn
Aric Dunn - avatar
0
right. but I need for it to print the try/except if someone types a string. and I cant see to figure it out.
14th Oct 2017, 4:32 PM
Aric Dunn
Aric Dunn - avatar