尝试制作一个随机数生成器,该生成器要求用户提供一个数字并将其与生成的数字进行比较。如何使比较的数字不会显示负数?
import random
number = random.randint(1, 100)
attempts = 1
print("I'm thinking of a number between 1 and 100.")
print("You only have one attempt.")
for tries in range(attempts):
geuss = int(input("Geuss a number: "))
if geuss != number:
print(f"You were {geuss-number} away!")
elif geuss == number:
print(f"Congratulations! You geussed the number.")
比方说,随机生成的数字是63,用户输入25。程序运行时,它说您在-38之外!我如何删除负号,使之说“您已经38岁了”?
答案 0 :(得分:2)
您将在f字符串中执行此操作的方式与在任何其他上下文中执行此操作的方式相同:通过调用abs
(绝对值函数)。
print(f"You were {abs(geuss-number)} away!")