我是一个非常新的Python用户(2.7)并且一直在学习Python的艰难之路课程,直到第37章,并决定阅读其他一些学习材料并再次阅读基础知识并进行练习那里。我一直在读这篇文章:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html
我刚刚这样做了:
3.1.4.1。研究生锻炼 写一个程序,Graduate.py,提示学生他们有多少学分。打印他们是否有足够的学分来毕业。 (在洛约拉大学芝加哥分校需要120学分。)
这是我的代码:
print "How many credits do you currently have: "
credits = raw_input("> ")
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
但不管我输入的是什么号码只是每次给出“抱歉没有足够的积分”作为答案,为什么?我试过移动一些东西并制作它>而不是> =但没有任何效果。我确定这是一个非常简单的东西我想念但我无法弄明白。
我已经在LPTHW课程中完成了几个与此类似的声明练习并且从未遇到过问题。
答案 0 :(得分:4)
raw_input()
返回一个字符串:
>>> credits = raw_input("> ")
> 150
>>> type(credits)
<type 'str'>
您需要将其投射到int
:
credits = int(raw_input("> "))
答案 1 :(得分:0)
在您的代码中,您在if语句中将str
类型与int
类型进行比较。所以它没有像你所想的那样工作。将credit
投射为int
print "How many credits do you currently have: "
credits = raw_input("> ")
credits = int(credits)
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
答案 2 :(得分:0)
我指的是安德鲁·哈灵顿(Andrew Harrington)博士的同一材料,并且我正在做同一程序,我的程序可能看起来很陈旧,因此,如果有人可以对其进行改进,我将不胜感激
def graduateEligibility(credits):
if credits >= 120:
print("Congratulations on successfully completing the course.....see you on graduation day!")
else:
print("Sorry! Your credits are below 120, please kindly retake the evaluaton tests")
def main():
E = float(input("Enter your English marks:"))
M = float(input("Enter your Mathematics marks:"))
P = float(input("Enter your Physics marks:"))
C = float(input("Enter your Chem marks:"))
Cf = float(input("Enter your Comp.Fundamentals marks:"))
Fin_Edu = float(input("Enter your finance marks:"))
Const = float(input("Enter your Constitutional.Stds marks:"))
R = float(input("Enter your Reasoning marks:"))
TotalCredits = (E+M+P+C+Cf+Fin_Edu+Const+R)
YourCredits = graduateEligibility(TotalCredits)
main()
为简单起见,我选了8个科目,每个科目有20个学分。
答案 3 :(得分:0)
您需要为此接受整数输入,并且还需要处理非整数输入。
print "How many credits do you currently have: "
try:
credits = int(raw_input("> "))
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
except ValueError:
print "Invalid input"
输出:
> 100
Sorry not enough credits
> 121
You have graduated!
> aaaa
Invalid input