Python实现Pig Latin小游戏实例代码

栏目: 编程语言 · Python · 发布时间: 6年前

内容简介:这篇文章主要介绍了Python实现Pig Latin小游戏实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下

前言:

本文研究的主要是 Python 实现pig Latin小游戏的简单代码,具体介绍如下。

Pig Latin是一个语言游戏。

步骤:

1.让用户输入一个英文单词
2.确保用户输入一个有效单词
3.将单词转换成Pig Latin
4.显示转换结果

一、Input

函数:raw_input()用于输出一个字符串并等待键盘输入某字符串,最后以Enter(或Return)结束输入

original = raw_input("Enter a word:") 
print original

上述中,控制台会输出What's your name?,并等待用户键盘输入一个字符串,直到遇到Entert(或Return)键结束,并将输入的字符串赋值给name

二、Check Empty

if len(original) > 0: 
  print(original) 
else: 
  print("empty") 

三、Check Alphabetical Characters

函数:isalpha()用于检查一个字符串中是否存在非字符符号,如果存在返回False,反之不存在,则返回True

original = raw_input("Enter a word:") 
if len(original) > 0 and original.isalpha(): 
  print(original) 
else: 
  print("empty") 

四、Create Some New Variables

pyg = 'ay' 
word = original.lower() 
first = word[0] 

上述,pyg是后缀;word是将原输入字符串小写化的结果;first是word字符串的第一个字母

五、Concatenate

new_word = word + first + pyg 

六、Slice

new_word = new_word[1:len(nwe_word)] 

上述new_word[1:len(new_word)]指的是字符串第二个字符到最后一个字符之间的局部字符串。

七、Result

pyg = 'ay' 
 
original = raw_input('Enter a word:') 
 
if len(original) > 0 and original.isalpha(): 
  print original 
  word = original.lower() 
  first = word[0] 
  new_word = word + first + pyg 
  new_word = new_word[1:len(new_word)] 
  print(new_word) 
else: 
  print 'empty' 

总结


以上所述就是小编给大家介绍的《Python实现Pig Latin小游戏实例代码》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to the Design and Analysis of Algorithms

Introduction to the Design and Analysis of Algorithms

Anany Levitin / Addison Wesley / 2011-10-10 / USD 117.00

Based on a new classification of algorithm design techniques and a clear delineation of analysis methods, Introduction to the Design and Analysis of Algorithms presents the subject in a coherent a......一起来看看 《Introduction to the Design and Analysis of Algorithms》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具