my while loop is not breaking when the user input reaches the number 10?

huangapple go评论69阅读模式
英文:

my while loop is not breaking when the user input reaches the number 10?

问题

我试图从用户那里获取数字输入,直到达到10,并会中断循环,然后遍历列表并检查它是奇数还是偶数。my while loop is not breaking when the user input reaches the number 10?

my while loop is not breaking when the user input reaches the number 10?

my while loop is not breaking when the user input reaches the number 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.my while loop is not breaking when the user input reaches the number 10?

my while loop is not breaking when the user input reaches the number 10?

my while loop is not breaking when the user input reaches the number 10?

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")

huangapple
  • 本文由 发表于 2023年5月21日 04:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定