逐梦者 发表于 2022-12-28 06:28:07

(求)在需要给变量重新赋值和打印结果的情况下,怎么写条件表达式呀

例如

"""验证角谷猜想"""

num = int(input("请输入一个整数:"))

while num > 1:

    print(num,"/",2,"=",int(num/2)) if (num%2 == 0) else print(num,"*",3,"+",1,"=",num*3+1)
    num = int(num/2) if (num%2 == 0) else num*3+1

循环下的代码能写成一个条件表达式吗?
就是( 执行语句 if 条件为True else 执行语句)的形式

lxping 发表于 2022-12-28 09:35:11

num = int(input("请输入一个整数:"))

while num > 1:
    if num%2 == 0:
      print(num, "/", 2, "=", int(num/2))
      num = int(num/2)
    else:
      print(num, "*", 3 , "+", 1, "=", num*3+1)
      num = num*3 + 1

isdkz 发表于 2022-12-28 10:12:19

num = int(input("请输入一个整数:"))

while num > 1:
    print(num,"/",2,"=", num := int(num/2)) if (num%2 == 0) else print(num,"*",3,"+",1,"=",num := num*3+1)

逐梦者 发表于 2022-12-28 19:27:36

isdkz 发表于 2022-12-28 10:12


十分感谢大佬!
页: [1]
查看完整版本: (求)在需要给变量重新赋值和打印结果的情况下,怎么写条件表达式呀