加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

SyntaxError:name’cows’在Python3.6中的全局声明之前被赋值

发布时间:2020-12-20 12:01:26 所属栏目:Python 来源:网络整理
导读:我正在尝试编辑循环中的全局变量cows和bulls但是得到此错误“SyntaxError:name’cows’在全局声明之前被分配” import randomrandom_no = random.sample(range(0,10),4)cows = 0bulls = 0#random_num = ','.join(map(str,random_no))print(random_no)user_i
我正在尝试编辑循环中的全局变量cows和bulls但是得到此错误“SyntaxError:name’cows’在全局声明之前被分配”

import random

random_no = random.sample(range(0,10),4)
cows = 0
bulls = 0
#random_num = ','.join(map(str,random_no))
print(random_no)
user_input = input("Guess the no: ")
for index,num in enumerate(random_no):
    global cows,bulls
    print(index,num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')

解决方法

Python没有块作用域,只有函数和类引入了新的作用域.

因为这里没有函数,所以不需要使用全局语句,牛和公牛已经是全局变量.

您还有其他问题:

> input()总是返回一个字符串.
>索引适用于字符串(你得到个别字符),你确定你想要吗?
> user_input [index] == num总是为假; ‘1’== 1测试两种不同类型的对象是否相等;他们不是.
> random_no中的user_input [index]也总是为false,random_no列表只包含整数,不包含字符串.

如果用户要输入一个随机数,请将input()转换为整数,并且不要使用enumerate():

user_input = int(input("Guess the no: "))
for num in random_no:
    if user_input == num:
        cows += 1
    elif user_input in random_no:
        bulls += 1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读