我的代碼如下:
`x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
sum = 0
for num in range(x, y 1):
islessthanorzero = int(x) <= 0 or int(y) <= 0
isgreaterthanx = int(x) > int(y)
if x.isnumeric() and y.isnumeric():
if islessthanorzero:
print('not greater than zero')
exit()
if isgreaterthanx:
print('not greater than y')
exit()
else:
print ('not numeric')
exit()
else:
sum = num
print(f"The sum of numbers between {x} and {y} is {sum}")
`
要求:用戶輸入2個值。從 x 到 y 的所有數字的總和條件:
- x 和 y 是數字
- x 和 y 大于零
- y 必須大于
- 使用 for 回圈計算從 x 到 y 的數字之和
程式必須確保在將 x 到 y 的所有數字的總和之前滿足所有條件,否則將終止程式。
if-else 的邏輯有效,但我無法在 for 回圈中實作。
請幫忙
uj5u.com熱心網友回復:
輸入給出 a在數學運算式中使用它們之前string需要將其轉換為 a integer。
所以我建議你將值轉換為integers:
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
uj5u.com熱心網友回復:
您的 if-else 條件放置錯誤:
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
s = 0
if x.isnumeric() and y.isnumeric():
if int(x) <= 0 or int(y) <= 0:
print('not greater than zero')
if int(x) > int(y):
print('not greater than y')
exit()
else:
s = sum(list(range(int(x), int(y))))
else:
print ('not numeric')
exit()
print(f"The sum of numbers between {x} and {y} is {s}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348118.html
