英文:
my while loop is not breaking when the user input reaches the number 10?
问题
我试图从用户那里获取数字输入,直到达到10,并会中断循环,然后遍历列表并检查它是奇数还是偶数。
我尝试过多次更改代码,但不太清楚我在做什么,我非常新手。
英文:
I'm trying to get number inputs from the user, till he reaches 10 and would break the while loop and go through the list and check if its odd or even.
ive tried to change the code a bunch of times, i dont really know what im doing im very new
答案1
得分: 1
Input函数默认返回一个字符串,将其转换为整数或浮点数。并且在检查之前追加,否则您将无法检查10是偶数还是奇数。
numbers = []
while True:
i = int(input("输入一个数字: "))
numbers.append(i)
if i == 10:
break
for num in numbers:
if num % 2 == 0:
print(f"{num} 是偶数")
else:
print(f"{num} 是奇数")
英文:
The Input function by default returns a str convert it to int or Float. And also append before checking or else you will not be able to check if 10 is even or odd.
numbers = []
while True:
i = int(input("Enter a Number: "))
numbers.append(i)
if i == 10:
break
for num in numbers:
if num%2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
答案2
得分: 0
如果输入的类型是字符串(str),你不能直接与整数比较。首先要使用`int()`将其转换为整数,然后再与10比较。
numbers = []
while True:
num = int(input("输入一个数字:"))
if num == 10:
break
numbers.append(num)
for num in numbers:
if num % 2 == 0:
print(str(num) + " 是偶数")
else:
print(str(num) + " 是奇数")
英文:
if int(num) == 10
or
if num == '10'
your input type is string (str) and you can't compare it to int... first convert it to int using int()
then compare to 10
numbers = []
while True:
num = int(input("Enter a number: "))
if num == 10:
break
numbers.append(num)
for num in numbers:
if num % 2 == 0:
print(str(num) + " is even")
else:
print(str(num) + " is odd")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论