我是靠谱客的博主 想人陪香氛,最近开发中收集的这篇文章主要介绍Python猜数字游戏代码报错的解决办法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在尝试输入执行经典猜字游戏程序时,出现了奇怪的异常错误。
让我们先来看一下原始代码(在AI Sweigart的著作《Python游戏编程快速上手(第4版)》一书的第20页):

import random

guessTaken = 0
print('Hello! What is your name?')
myName = input()

number = random.randint(1, 20print('Well,' + myName + ',I am thinking of a number between 1 and 20')

for i in range(6):
    print('Take a guess')
    guess = input()
    bguess = int(guess)

    if guess < number:
        print('Your guess is too low.')
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break
if guess == number:
    guessTaken = str(i)
    print('Good job!' +myName+ 'You guessed my number in ' +guessTaken + 'guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was:' + number + '.')
   

执行完毕,出现异常:

	number = random.randint(1, 20^
SyntaxError: invalid character '(' (U+FF08)

Process finished with exit code 1

查询了网上若干文章,希望解决该问题。…无奈,感觉没切中要点,不是我程序代码提示的问题的解决办法。
又搜索了CSDN相关文章,也没找到答案。困惑啊!…

重新审视代码,发现逻辑分为三个阶段:
1)输入参与游戏的姓名(即name)并欢迎游戏者;
2)输入猜字的数字,与随机数相比较,判断究竟是大,还是小;
3)判断是否猜中数字:猜中了,即报告猜中用了几次;未猜中,则公布随机数答案。

于是,尝试了分段开始测试代码。第一段测试时,剩余代码加注释(不影响代码执行,也不用重新输入代码)。
测试到第三段时,仍然提示错误。于是逐个检查代码,分析是否为print()函数打印输出时报错;细化每一句检查,并在字符串拼接时,考虑用前后空格表达。检查完毕,稍作调整,再次运行下面完整代码:

import random

guessTaken = 0
print('Hello! What is your name?')
myName = input()

number = random.randint(1,20)
print('Well,' + myName + ',I am thinking of a number between 1 and 20')

for i in range(6):
    print('Take a guess')
    guess = input()
    guess = int(guess)

    if guess < number:
        print('Your guess is too low.')
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break

if guess == number:
    guessTaken = str(i)
    print('Good job! ' + myName +'. You guessed my number in ' + guessTaken + ' guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was:' + number + '.')

执行结果如下:

Hello! What is your name?
Jackson
Well,Jackson,I am thinking of a number between 1 and 20
Take a guess
19
Your guess is too high.
Take a guess
16
Your guess is too high.
Take a guess
12
Good job! Jackson. You guessed my number in 2 guesses!
Process finished with exit code 0

经过测试,了解到输入编程和输入代码时,需要注意以下几点:
1)不要迷信书本,感兴趣的代码一定要运行通过!未运行通过的,需要尝试修改并通过;
2)需要特别注意书写习惯,充分理解语法和中英文标点区别,正确输入代码。

修业勤为贵,行文意必高。

*如果你觉得有帮助,请点赞并关注我;不定期交流,会受益匪浅哦。:-)

备注:我用的是Python 3.9.4最新版本,以及集成开发环境PyCharm Community 2020.3升级到PyCharm Community 2021.1版本。

最后

以上就是想人陪香氛为你收集整理的Python猜数字游戏代码报错的解决办法的全部内容,希望文章能够帮你解决Python猜数字游戏代码报错的解决办法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部