Python学习笔记(4)从一个猜字游戏开始

学习主题:改进那个猜数字的游戏,进一步学习基础语法
学习日期:2020-02-04
Python 版本:3.7.4

条件分支语法,注意冒号和缩近。

print("Let us play a game--- guess the number");
TheNum=input('please  input the number  ');
TheNum=int(TheNum)
print(TheNum)
temp=input('please  input your guessed number ');
GuessNum= int(temp);

if GuessNum==TheNum :
    print('Suceed,  Pass')
else:
    if GuessNum < TheNum:
        print('smaller than TheNum');  
    else:  #  GuessNum > TheNum
        print('bigger than TheNum');
    print('Try Agian');

这段代码较之前,给出了一个你的猜想结果比实际大还是小。但是你要想重新猜测试探,还得再次重新运行代码,好烦人,用户体验差!

基于上面,我们需要改进,这里要使用到while语句。

print("Let us play a game--- guess the number");
TheNum=input('please  input the number  ');
TheNum=int(TheNum)
print(TheNum)
flag=1
while flag==1:
    temp=input('please  input your guessed number ');
    GuessNum= int(temp);
    if GuessNum !=TheNum :
        flag=1
        if GuessNum < TheNum :
            print('Smaller ! than TheNum');  
        else:   
            print('Bigger  ! than TheNum');
            print('Try Agian');
    else:
        flag=0
print('Suceed,  Pass')

这段代码是缺点就是,如果你猜不对数字,难么这个游戏就得一直进行下去,直到你猜对。有些笨蛋就是猜不对,不必浪费时间了。那么,我们就得限制 猜测次数。

print("Let us play a game--- guess the number");
TheNum=input('please  input the number  ');
TheNum=int(TheNum)
print(TheNum)
flag=1
times=0;
while flag==1 and times <5: #and 是逻辑与
    temp=input('please  input your guessed number ');
    GuessNum= int(temp);
    times=times+1;
    if GuessNum !=TheNum :
        flag=1
        if GuessNum < TheNum :
            print('Smaller ! than TheNum');  
        else:   
            print('Bigger  ! than TheNum');
            print('Try Agian');
    else:
        flag=0
        print('Suceed,  Pass');
print('Game Over')
     

发布了75 篇原创文章 · 获赞 45 · 访问量 7321

猜你喜欢

转载自blog.csdn.net/hahahahhahha/article/details/104166801