繁体   English   中英

Python 单双

[英]Python Odd and Even

我是 python 的新手。我正在尝试编写一个程序来测试数字是否在给定范围之间,然后告诉您数字是奇数还是偶数。 我在检测它是奇数还是偶数的部分遇到问题。 似乎如果它只是重复我的偶数语句。 这是代码:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if num >= 1 and num <= 50:
        for num in range (1, 50):
            if (num % 2 == 0):
                print("Your number is even.")
        else:
            print("Your number is odd.")
        
    else:
        print("Try again. Number must be 1 through 50.")

我认为您根本不需要for循环,并且如果您的内部if-else忘记缩进else部分:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if num >= 1 and num <= 50:
        for num in range (1, 50):  # not needed
            if (num % 2 == 0):
                print("Your number is even.")
            else:  # here
                print("Your number is odd.")
    else:
        print("Try again. Number must be 1 through 50.")

for-else结构存在(并且非常简洁),但是您开始学习 Python,这是另一个故事了。

不,你不需要for循环:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if 1 <= num <= 50:
        if num % 2 == 0:
            print("Your number is even.")
        else:
            print("Your number is odd.")        
    else:
        print("Try again. Number must be 1 through 50.")

我认为你不需要 for 循环,删除 for 循环并重试。

while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
        if (num % 2 == 0):
            print("Your number is even.")
        else:  # here
            print("Your number is odd.")
else:
    print("Try again. Number must be 1 through 50.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM