Python:for循环之应用-Routine4

For循环的结构:首先是一个for,然后是一个可以用于存放各个元素的变量,经常用i,j,k表示计数器变量,接下来是in,然后是要遍历的序列,然后是一个冒号,最后是另起一行加Tab制表符的循环体。for循环会按顺序为序列中的每个元素执行一次循环体,当到达序列的末尾时,循环就结束了。用于存放元素的计数器变量如果在循环之前还不存在的话,也是会被直接创建的,并且计数器变量在循环体中也不一定会被使用到。举例子如下:

for i in "python":
    print(i)

会发现它把各个字符都打印在不同的行,我想把它们打印在一行,怎么办呢?

for letter in "Trouble":
    print(letter,end = " ")

此时,它们就会老老实实地待在一起了,要是嫌挨得不够近,可以把end后面双引号里面的空格删除,它们就会变成”trouble”了。end=” “的意思是自己指定结束形式,也就是打印完计算机不要以回车结束,而是以空格结束。
接下来给出一个for循环和range()函数结合的一个小程序:

print("I'll show you 20 numbers between 1 and 20:\n")
for i in range(1,21):
           print(i,end = " ")
print("\n\nIn range 20,show the numbers every 2 numbers:\n")
for i in range(1,21,2):
           print(i,end = " ")
print("\n\nCounting the numbers between 1 and 10 backwards:\n")
for i in range(10,0,-1):
           print(i,end = " ")

上面程序里面的循环序列是由range()函数给出的,该函数只在有需要的时候才会返回序列中的下一个值,如果给range()函数提供一个正整数,那就可以返回从零开始到给定数值(不包括它)的整数序列,如果给函数三个值,那么这三个值会分别作为起始点,结束点和计数单位,起始点是始终都会得到的值,而结束点却不包括在内。

Python提供了许多实用的函数和运算符,来操作包括字符串在内的各种序列。这些运算符和函数可以告诉你一些有关序列的简单而重要的信息,比如长度和是否含有特定元素。比如:

information = input("\nEnter a word that you want to know something about:\n")
length = len(information)
print("\nThe length of your information is :",length)
print("\nThe most beautiful letter I think in the English language 's'",end=" ")
if "s" in information:
           print("is in your information")
else:
           print("is not in your information.")

input("\nEnter the enter key to exit!")

其中用到了len()函数,它会对传给它的序列,返回该序列长度的响应。序列的长度包括它包含元素的数量,包括空格,感叹号之类的元素。
还用到了in运算符,在判断某个元素是否包含在某个序列时,可以用in。

下面贴出过去别人经常玩的一个Word Jumble游戏

新的个性化游戏规则我限定如下:游戏开始时,游戏者有权决定要不要进入游戏。游戏者需要从计算机给出的打乱的字母中猜中原来的单词是什么,游戏者只有5次机会猜中它,否则游戏会重新给出一个新的打乱字母顺序的单词去猜,当然此时游戏者可以选择退出游戏。

#Word Jumble
print("I am so happy that you can play this Word Jumble game with me!")
print("I'll give you a word that is scrambled.Your task is to unscramble it!")
print("And show me the right answer.")
yourwill = input("Do you accept this challenge?Yes or No:")
import random
WORDLIB = ('technique','architecture','heritage','gorgeous','fabulous','tremendous','application','heterostructure','electroluminescence','phosphorene','intriguing')

if yourwill.lower() == 'yes':

           input("Press the enter key to start!")
           while yourwill.lower() == 'yes':
                      counts = 1
                      word = random.choice(WORDLIB)
                      answer = word
                      newword = ''
                      while word:
                                 position = random.randint(0,len(word) - 1)
                                 if word:
                                            newword += word[position]
                                            print(word[position],end = " ")
                                            word = word[:position] + word[(position+1):]                      
                      yourguess = input("\nPlease enter your answer:")
                      while yourguess != answer and ((counts % 5) != 0):
                                 print("\nWrong!Guess it again!")
                                 yourguess = input("\nPlease change your answer:")
                                 counts += 1
                      if yourguess == answer:
                                 print("\nCongratulation!You made it.The answer is",answer)
                      else:
                                 print("\nI'm sorry.The answer is",answer)
                      yourwill = input("\nWant to challenge it again?Yes or No:")
           print("\nLooking forward to your next visiting!")
else:
           print("\nLooking forward to your next visiting!")
input("\n Enter the enter key to withdraw!")

编写这个游戏之前,我们要理解字符串及元组的不变性,能通过“+”运算符创建新的字符串及用“”+“”运算符连接其他元组成新的元组,理解切片的概念,会创建元组并会对其切片和索引。
注意:Python中常量一般全大写,但这只是约定俗成的东西,Python并不会阻止你用非大写的名字做常量,只是靠自觉。

其实可以将上面while循环改成for循环。你可以尝试一下。核心如下:

import random
WORDLIB = ("mood","happy","young")
answer = random.choice(WORDLIB)
newword = answer
word = ''
for i in range(len(answer)):
           position = random.randint(0,len(newword)-1)
           word += newword[position]
           newword = newword[0:position]+newword[(position+1):]
print(answer,'is scrambled to',word) 

Word Jumble升级版:加入了计分和提示。限制5次机会去赢得游戏,并在游戏者遇到困难时询问要不要给提示。

#Word Jumble升级版
print("I am so happy that you can play this Word Jumble game with me!")
print("I'll give you a word that is scrambled.Your task is to unscramble it!")
print("And show me the right answer.")
yourwill = input("Do you accept this challenge?Yes or No:")
import random
WORDLIB = ('technique','architecture','heritage','gorgeous','fabulous','tremendous','application','heterostructure','electroluminescence','phosphorene','intriguing')

if yourwill.lower() == 'yes':

           input("Press the enter key to start!")
           while yourwill.lower() == 'yes':
                      hinttimes = 1
                      counts = 1
                      word = random.choice(WORDLIB)
                      answer = word
                      newword = ''
                      while word:
                                 position = random.randint(0,len(word) - 1)
                                 if word:
                                            newword += word[position]
                                            print(word[position],end = " ")
                                            word = word[:position] + word[(position+1):]                      
                      yourguess = input("\nPlease enter your answer:")
                      while yourguess != answer and ((counts % 5) != 0):
                                 print("\nWrong!Guess it again!")
                                 if counts > 3 and hinttimes == 1:
                                            hint = input("Want a hint?Yes or No:")
                                            if hint.lower() == 'yes':
                                                       print("\nThe first letter is",answer[0])
                                                       yourguess = input("\nPlease give your new answer:")
                                                       counts += 1
                                                       hinttimes = 0
                                            else:
                                                       yourguess = input("\nPlease give your new answer:")
                                                       counts += 1
                                 else:
                                            yourguess = input("\nPlease go on to guess the answer:")
                                            counts += 1
                      if yourguess == answer:
                                 if hinttimes == 0:
                                            print("\nCongratulation!You made it.The answer is",answer,".Finally the score you have got is",(6-counts)*20-10,"points!")
                                 else:
                                            print("\nCongratulation!You made it.The answer is",answer,".Finally the score you have got is",(6-counts)*20,"points!")           
                      else:
                                 print("\nI'm sorry.The answer is",answer,".Finally the score you have got is 0 point!")
                      yourwill = input("\nWant to challenge it again?Yes or No:")
           print("\nLooking forward to your next visiting!")
else:
           print("\nLooking forward to your next visiting!")
input("\n Enter the enter key to withdraw!")

小程序:获取用户输入的一条信息,将其倒序输出

info = input("Enter a information that I will inverse it to you:")
inverse = ''
for i in range(len(info)-1,-1,-1):
           inverse += info[i]
print(inverse)

计算机与用户之间的小猜字游戏:

import random
LIB = ("kid","wild","elegant")
word = random.choice(LIB)
print("I have randomly chose a word,can you guess it?The lenght of the word is",len(word))
print("\nYou only have 5 chances to ask me if there is some letter in it. ")
print("\nAnd I only can just say yes or no.")
chance = 1
while chance <= 5:
           letter = input("\nTell me the letter you want to ask:")
           if letter in word:
                      print("\nYes")
                      chance += 1
           else:
                      print("\nNo")
                      chance += 1
answer = input("\nNow tell me the word you guess:")
if answer.lower() == word:
           print("\nYou are right!The word is",word,"!")
else:
           print("\nSorry!The word is",word,"!")

加一个小题:输出1到5000的所有的5和7的公因数,要求每20个打印成一行。

j = 0
for i in range(1,5000):
           if i % 5 == 0 and i % 7 == 0:
                      print(i,end = ' ')
                      j += 1
           if j != 0 and j % 20 == 0:
                      print("\n")
                      j = 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值