Skip to main content
 首页 » 编程设计

python之我怎样才能使这个 python 代码更短、更高效

2025年01月19日14xxx_UU

<分区>

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

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/elif/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: ")) 
    if choice < number: 
        print("Higher") 
    elif choice > number: 
        print("Lower") 
    else: 
        print("Well done!")