[英]How to remove negative signs in an f string expression?
尝试制作一个随机数生成器,该生成器要求用户提供一个数字并将其与生成的数字进行比较。 如何使比较的数字不会显示负数?
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岁了?
您将在f字符串中执行此操作的方式与在任何其他上下文中执行此操作的方式相同:通过调用绝对值函数abs
。
print(f"You were {abs(geuss-number)} away!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.