如何使这个python代码更短,更高效

时间:2017-12-05 18:11:48

标签: python

这是我尝试做更高/更低的游戏。

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

我是python的新手,我只是想知道有没有办法缩短代码以提高效率?不要认为需要两个if if / elif / else&#39;语句,但无法找到合并它们的方法。对不起,如果这是一个愚蠢的问题!

更新代码:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

4 个答案:

答案 0 :(得分:1)

你可以这样做:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
while True:
    try:
        choice = int(input("Please pick a number between 1 & 100: "))
    except ValueError:
        continue
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
        break

答案 1 :(得分:0)

以下是一个建议:使用保证不等choice的内容初始化number(例如,负数,“哨兵”)。然后你可以立即从while循环开始,因为条件第一次总是为真。

然后你可以删除第一个if / then / else块,并在while循环之外第一次调用input()

BTW,“短代码”并不总是“高效代码”:)

答案 2 :(得分:0)

您可以尝试这样的事情:

import random
print("A game of Higher or Lower")

number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))

while choice != number:
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")

    choice = int(input("Pick again: "))

print("Well done")

封装检查用户输入的代码也可能是一个好主意。

答案 3 :(得分:0)

if / else语句可以放在一行:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    s = 'Higher' if choice < number else ('Lower' if choice > number else 'Well done!')
    print(s)

如果要最小化字符数,请将var名称更改为&#34;姓名缩写&#34;像:

import random
print("A game of Higher or Lower")
n = random.randint(1, 100)
c = ""
while c != n:
    c = int(input("Please pick a number: "))
    s = 'Higher' if c < n else ('Lower' if c > n else 'Well done!')
    print(s)