Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Python 3.x - Fatal编程技术网

Python:仅循环打印最后一个值

Python:仅循环打印最后一个值,python,python-3.x,Python,Python 3.x,我的程序将奇数打印到一个特定的数字在数学上是可行的,但是,我打印每个奇数都有困难 出于某种原因,程序仅打印最终奇数: x=0 N=input('What is your number?') N=float(N) check=(N/2) if (check).is_integer()==1: print('Your number is even') index=N-N/2-1 while x<=index: x=2*index+1 pr

我的程序将奇数打印到一个特定的数字在数学上是可行的,但是,我打印每个奇数都有困难

出于某种原因,程序仅打印最终奇数:

x=0
N=input('What is your number?')
N=float(N)
check=(N/2)
if (check).is_integer()==1:
    print('Your number is even')
    index=N-N/2-1
    while x<=index:
        x=2*index+1
        print(x)
        index=index+1
else:
    print('Your number is odd')
    index=(N-1)/2
    while x<=index:
        x=2*index+1
        print(x)
        index=index+1
x=0
N=输入('您的号码是多少?')
N=浮动(N)
检查=(N/2)
如果(检查).is_integer()==1:
打印('您的号码是偶数')
索引=N-N/2-1

而你对奇数的计算是非常复杂的。。古怪的我不明白你想干什么。为什么不直接从
1
开始
x
,每次递增2,直到到达
N

x = 1
while x <= N:
    print(x)
    x += 2

我有几点建议

首先,您使用的是浮点数,但除非您要使用浮点数(带小数的数字),否则我建议您使用整数

,如果您试图检查一个数字是偶数还是奇数,您应该检查(%)运算符

第三,始终保持简单。除非需要,否则不要重复代码

下面是一个简单版本的程序示例

user_input=input('What is your number?')
user_input=int(user_input)
if user_input % 2 == 0:
    print('Your number is even')
else:
    print('Your number is odd')
for index in range(1, user_input+1, 2):
    print(index)
最后,请注意,如果放入垃圾输入(如“y7”),脚本将出错。要解决此问题,您应该/可以使用异常处理

user_input=input('What is your number?')
user_input=int(user_input)
if user_input % 2 == 0:
    print('Your number is even')
else:
    print('Your number is odd')
for index in range(1, user_input+1, 2):
    print(index)