例如,如果我想输入一个类似于' duck'的字符串,我需要拼出的函数:
d
ü
ç
ķ
但没有参数 - 我该怎么做?
def spell():
'''Returns every character in a word or phrase'''
print(input('Enter a word: '))
for n in range(len(n)):
print(n)
我试图使上面的代码工作,但我遇到了麻烦,因为我尝试的所有内容都提示错误消息,该消息与未定义的变量有关。我该如何更改我的代码?
答案 0 :(得分:2)
使用var x = 10; // x is 10
function main() {
var x; // x declaration is "hoisted"
document.write("<br>x1 is" + x); // x1 is undefined
x = 20; // x is 20
if (x > 0) {
x = 30; // x is 30
document.write("<br>x2 is" + x);// x2 is 30
}
x = 40; // x is 40
var f = function(x) { // x is 50
document.write("<br>x3 is" + x);// x3 is 50
}
f(50);
}
main();
-
str.join
答案 1 :(得分:1)
你做错了一些事。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Roles.IsUserInRole(User.Identity.Name, "admin") Then
rUser.Text = "You are not authorzied"
Else
rUser.Text = "WELCOME ADMIN"
End If
End Sub
如果您正在使用Python3,则必须将def spell():
'''Returns every character in a word or phrase'''
word = raw_input('Enter a word: ')
for i in word:
print(i)
更改为raw_input
,因为Python3中不存在input
,其工作方式与input
类似。< / p>
答案 2 :(得分:1)
你的问题在这里:
for n in range(len(n))
问题具体在于,此时n
尚未分配,因此虽然它作为迭代器(for n
)有效但它失败了在声明的len(n)
部分。
解决方案首先要确保您将分配给此变量,或者使用迭代器覆盖有效对象,例如:
def spell():
'''Returns every character in a word or phrase'''
n = input('Enter a word: ') # assign the input to 'n'
for n in range(len(n)):
print(n)
(我可能会使用不同的变量名,因为迭代器使用相同的名称,输入可能会令人困惑)
或者你可以这样做:
def spell():
print [n for n in range(len(input('Enter a word: ')))]
"""
*for python 2.x:
print [n for n in range(len(raw_input('Enter a word: ')))]
*to return a list of the letters, do:
return [n for n in range(len(raw_input('Enter a word: ')))]
"""