Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python条件产生错误的结果_Python_While Loop - Fatal编程技术网

python条件产生错误的结果

python条件产生错误的结果,python,while-loop,Python,While Loop,我是python新手,我有一个关于while循环的问题 有人能解释一下我的代码到底发生了什么,为什么它会给我一个不正确的结果吗 这是我的代码: age=20 while age >= 10: age=int(input("what is your age?")) print("your age is >= 10") 对此的回应是: what is your age? 9 "your age is >= 10" 我不明白这一点。我使用的是windo

我是python新手,我有一个关于while循环的问题

有人能解释一下我的代码到底发生了什么,为什么它会给我一个不正确的结果吗

这是我的代码:

age=20

while age >= 10:
    age=int(input("what is your age?")) 
    print("your age is >= 10")
对此的回应是:

  what is your age? 9
  "your age is >= 10"

我不明白这一点。我使用的是windows7&python3

问题是,在询问年龄后,您正在打印您的年龄>=10,但实际上没有检查他们首先输入的年龄。如果打印时间不大于等于10,则应在打印周围使用条件语句以防止打印

age=20

while age >= 10:
    age=int(input("what is your age?"))
    if age >= 10: 
        print("your age is >= 10")

你试过运行这个代码吗?这将有助于澄清

Input是一个函数,它接受字符串what is your age?,提示用户,并在命令行中返回用户输入的答案。然后,函数int将用户答案从字符串转换为整数。之后,将此整数指定给变量age=,然后打印一条消息,说明您的年龄>=10

每次循环运行时,程序都会询问用户的年龄,并将其分配给可变年龄。然后while循环检查条件:年龄是否等于或大于10岁?年龄>=10岁。如果不是,它将继续循环。只有当用户输入的年龄小于10岁时,它才会退出循环

希望能有帮助

我建议将while age>=10:while改为True,并在if中添加一个else:break分支,这样该条件就不会被检查两次。