4.1 猜數遊戲。在程序中預設一個0~9之間的整數,讓用戶經過鍵盤輸入所猜數字,若是大於預設的數,顯示「遺憾,太大了」;若是小於預設的數,顯示「遺憾,過小了」;如此循環,直至猜到該數,顯示「預測N次,你猜中了!」,其中N是用戶輸入數字的次數。
secret = 4
#print(secret)
print('------猜數字遊戲!-----')
num = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(num)
N=1
while guess != secret:
if guess > secret:
print('遺憾,太大了!')
else:
print('遺憾,過小了!')
num = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(num)
N=N+1
#print(secret)
print('------猜數字遊戲!-----')
num = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(num)
N=1
while guess != secret:
if guess > secret:
print('遺憾,太大了!')
else:
print('遺憾,過小了!')
num = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(num)
N=N+1
print('預測{:.0f}次,您猜對了!'.format(N))
print('遊戲結束,再見!^_^')
print('遊戲結束,再見!^_^')
4.4 猜數遊戲。改編程序練習題4.1,讓計算機隨機產生一個預設數字,範圍在0~100之間,其餘遊戲規則不變。
import random
secret = random.randint(0,100)
#print(secret)
print('------猜數字遊戲!-----')
temp = input('猜數字遊戲開始,請輸入數字0-100:')
guess = int(temp)
N=1
while guess != secret:
if guess > secret:
print('遺憾,太大了!')
else:
print('遺憾,過小了!')
temp = input('猜數字遊戲開始,請輸入數字0-100:')
guess = int(temp)
N=N+1
secret = random.randint(0,100)
#print(secret)
print('------猜數字遊戲!-----')
temp = input('猜數字遊戲開始,請輸入數字0-100:')
guess = int(temp)
N=1
while guess != secret:
if guess > secret:
print('遺憾,太大了!')
else:
print('遺憾,過小了!')
temp = input('猜數字遊戲開始,請輸入數字0-100:')
guess = int(temp)
N=N+1
4.7 用異常處理改造4.1,使其能接收並處理用戶的任何輸入。
import random
secret = 4
#print(secret)
N=1
a=1000
while secret!=a:
try:
temp = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(temp)
if guess>secret:
print('遺憾,太大了!')
elif guess<secret:
print('遺憾,過小了!')
elif guess==secret:
N=N+1
break
except ValueError :
print(" is not number")
N=N+1
print('預測{:.0f}次,您猜對了!'.format(N))
secret = 4
#print(secret)
N=1
a=1000
while secret!=a:
try:
temp = input('猜數字遊戲開始,請輸入數字0-9:')
guess = int(temp)
if guess>secret:
print('遺憾,太大了!')
elif guess<secret:
print('遺憾,過小了!')
elif guess==secret:
N=N+1
break
except ValueError :
print(" is not number")
N=N+1
print('預測{:.0f}次,您猜對了!'.format(N))
原文出處:https://www.cnblogs.com/sunblingbling/p/11605322.htmlhtml