简体   繁体   English

如何让 Python 从 1 打印到用户输入?

[英]How do I get Python to print from 1 to user input?

I'm trying to solve the scenario with these conditions:我正在尝试使用以下条件解决该场景:

  1. Ask the user to enter a number要求用户输入一个数字

  2. 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.如果是偶数,则不显示该数字。

  3. 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.

相关问题 更新python中的字典,如何从用户那里获取输入? - Update dictionary in python, how do I get input from user? 如何在Python 2中从键盘获取用户输入? - How do I get user input from the keyboard in Python 2? 调用函数进行打印时,如何从我的void函数中获取用户输入? - when calling a function to print, how do i get it to get user input from my void function? 如何根据用户输入显示if语句? - How do I get if statements to print based on user input? 如何打印用户从该列表中输入名称的完整列表? PYTHON - How do I print a full list where a user has input a name from that list? PYTHON 如何从用户输入中捕获矩阵并在用户输入时将其打印出来? - How do I capture a matrix from a user input and print it out as the user input it? Python 生成器:如何根据用户输入(要打印多少对)从两个不同的列表中生成对 - Python Generator: How do I generate pairs from two different lists based on user input (of how many pairs to print) 如何在 python(Kivy 框架)中获取用户输入 - How do I get user input in python (Kivy framework) 如何让用户在Python 3中输入数字? - How do I get the user to input a number in Python 3? 如何获得用户输入以引用Python中的变量? - How do I get user input to refer to a variable in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM