Python--my first try!

本文详细介绍了使用Python3.6.0实现的猜数游戏,包括常见错误如语法错误和类型错误的解决方法,以及代码缩进的重要性。此外还讲解了Python中print函数的用法变化和变量命名规范。

我所用的编译器是:Python 3.6.0

我之所以在一开始就说我的编译器是因为不同的编译器,不同的版本在代码的写法上会有一些区别!

比如:在我所用的版本3中print的用法是Print (“hello world!“) ,而在之前的版本2中则是print “hello world!“,不需要括号。

>>> print ("The secret number is:",secret)
The secret number is: 32
>>> print "The secret number is:",secret
SyntaxError: Missing parentheses in call to 'print'

这是语法错误,意味着键入的某个内容不是正确的Python代码。

根据参考书我运行了一些代码,以下面的“猜数游戏”的代码为例:

import random
secret=random.randint(1,99)
guess=0
tries=0
print("Anoy!I'm the Dread Pirate Roberts,and I have a secret!")
print("This is a number from 1 to 99.I will give you 6 tries.")
while guess!=secret and tries<6:
  guess=int(input("What's yer guess?"))
  if guess<secret:
        print ("Too low,ye scurvy dog!")
  elif guess>secret:
     print("Too high,landlubber!")
  tries=tries+1

if guess==secret:

  print("Avast!ye got it!Found my secret,ye did!")
else:
    print ("No more guess!Better luck next time,matey!")
    print ("The secret number is:",secret)

1.在上述代码中,课本参考代码第八行是 guess=input("What's yer guess?"),所得运行结

果出现错误:TypeError: '<' not supported between instances of 'str' and 'int';

这是因为input()返回的数据类型是str,不能直接和整数进行比较,必须先把str换成整数;用int()实现;

2.注意:

  • 缩进:第13行代码如果没有缩进则循环次数无限制,即如果猜不对会一直循环下去。
  • print的用法
  • 变量命名规则:区分大小写;变量名必须以字母或者下划线字符开头;变量名中不能包含空格;

 

转载于:https://www.cnblogs.com/ST-2017/p/7208468.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值