我不能在这个计划中重新分配更大的价值。 (蟒蛇)

时间:2017-07-24 23:19:13

标签: python

这是我迄今为止所做的。它产生2个连续的整数,然后增加,第三个变小,它按随机顺序排列。

import random

new_k = (random.randint(0 , 100))
k = (random.randint(0 , 100))

while k >= new_k :

    print(k)
    new_k = k

1 个答案:

答案 0 :(得分:1)

它确实将此处k的更大价值重新分配给new_k

我在ifelse部分添加了print语句,将新分配的值打印到new_k,然后我在IDLE上运行它并按程序运行。

import random

new_k = 1
k = (random.randint(0 , 100))
if k >= new_k:
    print("Greater Use Case")
    print(k)
    new_k = k
    print(new_k)
else:
    print("Smaller Use Case")
    print(k)
    print(new_k)

IDLE中的示例运行

========= RESTART: C:/sample.py =========
Greater Use Case
9
9
>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
8
8
>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
55
55
>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
13
13

EDIT:如果你希望它按递增顺序排列,那么你的初始代码是不正确的,你需要编写一个迭代结构。我给你一个非常基本的实现,您可以根据需要进行编辑,但它会让您清楚地知道值正在增加,当它减少时,它会退出。

import random

new_k = 1
while (True):
    k = (random.randint(0 , 100))
    if k >= new_k:
        print("Greater Use Case")
        new_k = k
        print("k=" + str(k) + "; new_k=" + str(new_k) + "\n")
    else:
        ## NOTE: i quit here when it is decreasing
        print("Smaller Use Case")
        print("k=" + str(k) + "; new_k=" + str(new_k) + "\n")
        break

示例运行

========= RESTART: C:/sample.py =========
Greater Use Case
k=83; new_k=83

Smaller Use Case
k=2; new_k=83

>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
k=51; new_k=51

Greater Use Case
k=69; new_k=69

Greater Use Case
k=78; new_k=78

Smaller Use Case
k=61; new_k=78

>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
k=22; new_k=22

Greater Use Case
k=100; new_k=100

Smaller Use Case
k=34; new_k=100

>>> 
========= RESTART: C:/sample.py =========
Greater Use Case
k=35; new_k=35

Smaller Use Case
k=28; new_k=35