python内容限制_将用户输入限制为Python中的范围

在下面的代码中,您将看到它要求“移位”值.我的问题是我想将输入限制为1到26.

For char in sentence:

if char in validLetters or char in space: #checks for

newString += char #useable characters

shift = input("Please enter your shift (1 - 26) : ")#choose a shift

resulta = []

for ch in newString:

x = ord(ch) #determines placement in ASCII code

x = x+shift #applies the shift from the Cipher

resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != \

' ' else ch) # This line finds the character by its ASCII code

我怎么这么容易?

解决方法:

使用while循环继续询问输入,直到您收到您认为有效的内容:

shift = 0

while 1 > shift or 26 < shift:

try:

# Swap raw_input for input in Python 3.x

shift = int(raw_input("Please enter your shift (1 - 26) : "))

except ValueError:

# Remember, print is a function in 3.x

print "That wasn't an integer :("

你还希望在int()调用周围有一个try-except块,以防你得到一个ValueError(如果他们输入一个例子).

请注意,如果使用Python 2.x,则需要使用raw_input()而不是input().后者将尝试将输入解释为Python代码 – 这可能非常糟糕.

标签:python,range

来源: https://codeday.me/bug/20190714/1460043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值