[英]How to set an if statement to less than and greater than at once on python?
[英]How to count the number greater than and less than a given set of numbers in python
Python 序列來統計分數大於和小於 50 的科目數。分數 50 及以下視為失敗。
樣本輸入
科目數:
5
輸入標記:
65
51
34
46
54
樣品 OUTPUT
子通過:3
子失敗:2
我的計划:
x=int(input("No. of subjects: \n"))
print("Enter marks:")
for i in range(x):
y=[int(input())]
count=0
h=0
for j in y:
if j>50:
count=count+1
if j<50:
h=h+1
print("Sub passed: " + str(count))
print("Sub failed: " + str(h))
上面的程序在得到輸入后沒有返回任何值。
它可以更整潔一點:
x=int(input("No. of subjects: \n"))
print("Enter marks:")
y= [int(input()) for i in range(x)]
passed = len([y_p for y_p in y if y_p > 50])
not_passed = len([y_n for y_n in y if y_n< 50])
print(passed) #According to question would print: 3
print(not_passed) #According to question would print: 2
首先,您使用列表理解創建一個包含所有輸入的列表。 然后,您制作另一個列表,其中條件已通過和未通過。
您需要在循環之外定義count
和h
:
x=int(input("No. of subjects: \n"))
print("Enter marks:")
count = 0
h = 0
for i in range(x):
y=[int(input())]
for j in y:
if j>50:
count=count+1
if j<50:
h=h+1
print("Sub passed: " + str(count))
print("Sub failed: " + str(h))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.