改進咱們的小遊戲shell
概有如下幾個方面須要改進:dom
猜錯的時候程序應該給點提示,例如告訴用戶輸入的值是大了仍是小了。ide
每運行一次程序只能猜一次,應該提供屢次機會給用戶猜想。函數
每次運行程序,答案能夠是隨機的。由於程序答案固定,容易致使答案外泄。spa
條件分支orm
第一個改進要求:猜錯的時候程序提示用戶當前的輸入比答案大了仍是小了。
遊戲
Python 的比較操做符input
>左邊大於右邊it
>=左邊大於等於右邊ast
<左邊小於右邊
<=左邊小於等於右邊
==左邊等於右邊
!=左邊不等於右邊
Python的條件分支語法:
if 條件 :
條件爲真(True)執行的操做
else:
條件爲假(False)執行的操做
while循環
第二個改進要求:程序應該提供屢次機會給用戶猜想,專業點來說就是程序須要重複運行某些代碼。
請用紅筆圈出你認爲須要進行循環的代碼:
print('------------------------------------')
temp = input("不妨猜一下我如今內心想的是哪一個數字:")
guess = int(temp)
while guess!==8:
temp=input("猜錯了,請從新輸入:")
guess=int(temp)
if guess == 8:
print("我草,你是我內心的蛔蟲嗎?!")
print("哼,猜中了也沒有獎勵!")
else:
if guess>8:
print("哥,大了")
else:
print("小了")
print("遊戲結束,不玩啦^_^")
while循環
Python的While循環語法:
while 條件 :
條件爲真(True)執行的操做
這裏咱們給你們的提示是:使用and邏輯操做符
Python的and邏輯操做符能夠將任意表達式鏈接在一塊兒,並獲得一個布爾類型的值。
>>> 3>2 and 3>4
False
>>> 3>2 and 3<4
True
>>> (3>2) and (3<4)
True
>>>
引入外援
第三個改進要求:每次運行程序產生的答案是隨機的。
咱們須要引入外援:random模塊
這個random模塊裏邊有一個函數叫作:randint(),Ta會返回一個隨機的整數。
咱們能夠利用這個函數來改造咱們的遊戲!
import random
secret = random.randint(1,10)
print('****************小遊戲******************')
temp = input("不妨猜一下我如今內心想的是哪一個數字:")
guess = int(temp)
while guess != secret:
temp = input("哎呀,猜錯了,請從新輸入吧:")
guess = int(temp)
if guess==secret:
print("我想什麼你都知道?")
print("哼,猜中了也沒有獎勵!")
else:
if guess > secret:
print("哥,大了")
else:
print("嘿,小了")
print("遊戲結束,不玩啦")
閒聊之Python的數據類型
整型
布爾類型
浮點型
E記法
>>> a=0.0000000000000000025
>>> a
2.5e-18
>>> 1500000000000
1500000000000
>>> 1.5E11
150000000000.0
>>> 15E10
150000000000.0
>>> 1.5e4
15000.0
>>> True + True
2
>>> True + False
1
>>>
數據轉換
>>> a="520"
>>> b=int(a)
>>> b
520
>>> b=int("小明")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
b=int("小明")
ValueError: invalid literal for int() with base 10: '小明'
>>> a=5.99
>>> c=int(a)
>>> c
5
>>> a="520"
>>> b=float(a)
>>> b
520.0
>>> a=520
>>> b=float(a)
>>> b
520.0
>>> a=5.99
>>> b=str(a)
>>> b
'5.99'
>>> c=5e10
>>> b=str(c)
>>> b
'50000000000.0'
>>>
>>> str="I Love Python"
>>> str
'I Love Python'
>>> c=str(3)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
c=str(3)
TypeError: 'str' object is not callable
>>>
得到關於類型的信息
type()
isinstance()
>>> a="520"
>>> type(a)
<class 'str'>
>>> type(5.2)
<class 'float'>
>>> type(1)
<class 'int'>
>>> type(True)
<class 'bool'>
>>> a="520"
>>> isinstance(a,str)
True
>>>isinstance(a,int)
False