简体   繁体   English

Python 交互窗口不断打开或运行脚本

[英]Python Interactive Window keeps opening a script instead or running it

I keep trying to run this loop, which is meant to register numbers above or below 50 in a random set of 10 loops.我一直在尝试运行这个循环,这意味着在 10 个循环的随机集合中注册大于或小于 50 的数字。

import random, string
N = random.sample(range(1,100),10)
if N > 50
        cntOver += 1
if N <= 50
        cntUnder += 1
cntOver = 0; cntUnder = 0
print cntOver, cntUnder

I'm not sure if I wrote something wrong with it, but every time I try to run it with Python's interactive window, it just opens up the script file instead of running it.我不确定我是否写错了什么,但是每次我尝试使用 Python 的交互式窗口运行它时,它只是打开脚本文件而不是运行它。 I admit I am a complete novice here, so if the solution is simple don't be afraid to call me dim.我承认我在这里完全是新手,所以如果解决方案很简单,请不要害怕称我为昏暗。

  1. N is a list, so you can not compare N with 50. You should use a for-loop. N 是一个列表,因此您不能将 N 与 50 进行比较。您应该使用 for 循环。
  2. You should initialize cntOver and cntUnder first.您应该首先初始化 cntOver 和 cntUnder。 Therefore, the correct way is following:因此,正确的方法如下:
import random, string
N = random.sample(range(1,100),10)
cntOver = 0; cntUnder = 0
for i in N:
    if i > 50:
        cntOver += 1
    if i <= 50:
        cntUnder += 1
print (cntOver, cntUnder)

The better way is using the built-in function sum(), where we can use list as an input.更好的方法是使用内置函数 sum(),我们可以使用 list 作为输入。 check how to use it: https://www.w3schools.com/python/ref_func_sum.asp检查如何使用它: https : //www.w3schools.com/python/ref_func_sum.asp

import random, string
N = random.sample(range(1,100),10)
cntOver = sum(i > 50 for i in N)
cntUnder = sum(i <= 50 for i in N)
print (cntOver, cntUnder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM