[英]Python: Loop only printing last value
My program to print the odd numbers up to a certain number mathematically works, however, I'm having trouble printing every odd number. 我的程序可以将数学上的奇数打印到一定数量,但是我在打印每个奇数时遇到了麻烦。
For some reason the program only prints the final odd number: 由于某种原因,程序仅输出最终的奇数:
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
Your counting of the odd numbers is very.. odd . 您对奇数的计数非常.. 奇数 。 I cannot make out what you were trying to do. 我无法弄清楚你想做什么。 Why not simply start x
at 1
and increment by 2 each time until you get to N
? 为什么不简单地从1
开始x
并每次增加2直到达到N
?
x = 1
while x <= N:
print(x)
x += 2
You don't need to use float
values here; 您无需在此处使用float
值; stick with int
and use the %
modulus (remainder) operator; 坚持使用int
并使用%
模数(余数)运算符; this has the advantage you can then use a range()
to produce all odd numbers up to N
: 这样的好处是您可以使用range()
生成所有不超过N
奇数:
N = int(input('What is your number?'))
if N % 2 == 0:
print('Your number is even')
else:
print('Your number is odd')
for x in range(1, N + 1, 2):
print(x)
There are a few suggestions I'd make. 我会提出一些建议。
First , you're using a float but unless you're going to be using floating point numbers (numbers with a decimal) I'd recommend you stick with integers. 首先 ,您使用的是浮点数,但除非您要使用浮点数(带小数的数字),否则我建议您坚持使用整数。
Second , if you're trying to check whether a number is even or odd, you should check out the modulo (%) operator. 其次 ,如果要检查数字是偶数还是奇数,则应检出模 (%)运算符。
Third , always keep things simple. 第三 ,始终保持简单。 Don't repeat your code unless you need to. 除非需要,否则不要重复您的代码。
Here is an example of a simpler version of your program. 这是您的程序的简单版本的示例。
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)
Finally, be aware that your script will error if you put in garbage input, like "y7" - to fix this you should/can use exception handling. 最后,请注意,如果您输入“ y7”之类的垃圾输入,您的脚本将出错-要解决此问题,您应该/可以使用异常处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.