Python--my first try!

我所用的编译器是: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