![](/img/trans.png)
[英]I'm a beginner to python and don't understand what's wrong with my code. I'm using pynput
[英]Im a beginner and don't understand what's wrong with my code
所以我试图让它如果一个数字低于 50,我的代码将打印出 Freestyle,如果它在 51-100 的范围内,它将打印蛙泳,最后如果它高于 101,它将打印出蝴蝶。
我正在努力为我的游泳伙伴和我的教练设置它,以使练习更有趣。
编辑我没有收到任何 output。
这是目前我的代码:
import random
def swimming():
x = random.randint(1, 150)
if x <= 50:
print("Freestyle")
elif x >= range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
import random
def swimming():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
swimming()
这将为您提供 output。
由于您没有发布自己的代码,因此这是我编写的一些快速代码,我认为它们可以满足您的要求:
def fun(x):
if x < 51: # Below 51 (0-50)
print("Freestyle")
elif x > 100: # Above 100 (101+)
print("Butterfly")
else: # In between (51-100)
print("Breaststroke")
其中x
是您作为参数放入 function 的数字。
您的代码只需要“def”,这意味着“定义”(或者至少是我的解释)。 为此(即“运行脚本”),您还需要在最后调用它。 此外, range 就像一个列表,而不是特定的 2 点,因此调用 >= range 不起作用。
您的代码应如下所示(最小更改)
import random
def swimming():
x = random.randint(1, 150)
if x <= 50:
print("Freestyle")
elif x in range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
swimming()
注意,此时它会返回一个随机值,不是用户指定的。 如果你真的想输入一个值,检查你想游泳的风格,然后循环回来,应该更像这样
import random
def swimming():
print('What is your number?')
try:
x = float(input())
if x <= 50:
print("Freestyle")
elif x in range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
except:
print('Input a number please')
while True:
answer = input('Do you want to continue? (Y/N)\n')
if answer.lower() == 'y' or answer.lower() == 'yes':
swimming()
else:
print('Thank you for playing.')
input('Press enter to exit.')
break
def 块中的“try”和“except”是为了确保输入是一个数字(integer 或小数)。 “while True”循环用于“持续工作”(只要您输入“y”或“yes”或“Y”或“YES”)。 如果您不喜欢这样,请删除整个块,然后继续“游泳()”
保持良好的工作。
def swimming():
for i in range(5):
x=random.randint(1,150)
if x<=50:
print("Freestyle")
elif x>=51 and x<=100:
print("Breaststroke")
else:
print("Butterfly")
swimming()
您可以使用第一个 for 循环尽可能多地获取输入。 我认为使用逻辑运算符更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.