[英]How do I get Python to print from 1 to user input?
I'm trying to solve the scenario with these conditions:我正在尝试使用以下条件解决该场景:
Ask the user to enter a number要求用户输入一个数字
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number.从 1 数到用户输入的数字,如果每个数字是奇数,则将其显示在单独的行上。 If it is an even number, do not display the number.
如果是偶数,则不显示该数字。
If the user enters a number that is 0 or less, display error如果用户输入一个小于等于 0 的数字,则显示错误
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:我的代码如下,我似乎无法满足 <= 0 print("error) 条件:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
You have to check the condition num <= 0
as soon as the user enters the number:用户输入数字后,您必须检查条件
num <= 0
:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)
Your solution will be:您的解决方案将是:
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run.您需要在从 1 循环到 num 之前打印错误,因为如果该值小于 0,则循环将不会运行。 I hope you understand.
我希望你明白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.