2017-02-17 90 views
1

這是我的代碼,我想它要經過,並選擇它適合於哪一類,但它總是給我F.爲什麼我的if語句在這個分級代碼中不起作用?

import random 

def rand(start, stop): 
    print random.randint(start,stop) 

def grader(rand): 
    print "Your test score is " 
    x = rand(50, 100) 
    if x >= 90: 
    print "which is an A." 
    elif x <= 89 and x >= 80: 
    print "which is a B." 
    elif x <= 79 and x >= 70: 
    print "which is a C." 
    elif x <= 69 and x >=60: 
    print "which is a D." 
    else: 
    print "which is a F." 
+4

'print'不是'return'。 – user2357112

+0

爲什麼你需要和random.randint()完全相同的函數? – Barmar

+0

我的老師讓我把它放在:/ – Hat

回答

0

,而不是返回random.randint(start,stop)的,你打印。

變化

def rand(start, stop): 
    print random.randint(start,stop) 

def rand(start, stop): 
    return random.randint(start,stop) 
+0

OMG THANK YOU !!!!!!我的老師給了我那段代碼,所以我從來沒有想過要看那裏! – Hat

0

rand函數返回None,因爲它是印刷的,而不是返回一個值。另外,最好的做法是將其命名爲更具描述性的內容,如get_randomget_random_number。另外,您的get_random功能確實與randint的功能完全相同,但我會給您帶來疑問的好處(需要添加更多功能?)。

作爲獎勵,我已經包含了一個例子,知道如何知道bisect庫對於這些類型的價值交叉點問題是完美的!

實施例:

import bisect, random 

def get_random(start, stop): 
    return random.randint(start,stop) 

def match_grade(score): 
    breakpoints = [60, 70, 80, 90] 
    grades = ["which is a F.", "which is a D.", 
    "which is a C.", "which is a B.", "which is an A."] 
    bisect_index = bisect.bisect(breakpoints, score) 
    return grades[bisect_index] 

random_number = get_random(50, 100) 
grade_range = match_grade(random_number) 
print "Your test score is {}, {}".format(random_number, grade_range) 

樣本輸出:

Your test score is 63, which is a D. 
相關問題