[Python]終極密碼

Posted by John on 2018-03-05
Words 270 and Reading Time 1 Minutes
Viewed Times

摁,就是終極密碼,沒什麼好講的。

比較值得提的是要做輸入的防呆,也就是說不能輸入小數、英文…

對於這個要求使用了try…except…解決了,原理大概是input()會回傳一個String,那如果對這個字串作轉型變成int呢?會有兩種情況:

  1. 該字串本來就是可以轉成int的字串,Ex: “123”、”9”…,那就可以很順利的轉型
  2. 該字串本來不是可以轉乘int的字串,Ex: “3.14”、”abc”…,在轉型的時候會產生ValueError,所以就可以透過except去進行例外處理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import random

ans = random.randint(0,100)
range_max = 100
range_min = 0
is_gameOver = False

def game_start():
print(ans)
while is_gameOver == False:
print("Guess a number between",range_min,"and",range_max,":")
try:
#Since input() will return a string,explicit convet int() will work correct when we input is an integer
#if we input a float, then int() will cause ValueError
guess = int(input())
except ValueError:
print('Your input doesnt an Integer!')
continue
check_fun(guess,ans)
def check_fun(guess,ans):
global range_max,range_min,is_gameOver
if guess == ans:
is_gameOver = True
print("Congulation!!You are guess the correct number!")
elif guess ans
range_max = guess - 1
print("You guess wrong!!Guess a number between",range_min,"and",range_max,":")

if __name__ == '__main__':
game_start()

>