我遇到了这个问题,其中replace函数调用大写函数,我需要做的是,我需要main函数调用其他函数(因此先调用大写,然后是replace)。我还需要更改交互区域。我的意思是,现在大写函数正在向用户询问字符串,但是我需要main函数先向用户询问一个字符串,然后调用大写函数,然后调用replace函数。
def uppercase():
cap_letters = input("Please enter your string here: ")
new_uppercase=''
for letters in cap_letters:
if ord(letters) > 96:
new_uppercase += chr(ord(letters)-32)
else:
new_uppercase += letters
print(new_uppercase)
return new_uppercase
def replace():
old,new = [],[]
newString = ""
new_uppercase = uppercase()
string = new_uppercase
char = input("Change: ")
toThis = input("Change " + char + " to this: ")
for x in range(0,len(string)):
old.append(string[x])
for y in range(0,len(old)):
if old[y] != char:
new.append(old[y])
else:
new.append(toThis)
for z in range(0,len(new)):
newString+=new[z]
print(newString)
def main():
print("Hello, And Welcome to this Slang Program")
uppercase()
# write the part of the program that interacts with the user here
replace()
main()
答案 0 :(得分:0)
您正在尝试在函数之间传递值。您需要return
来自每个函数的值,以便父函数可以使用它们。像这样传递值:
def function2(foo):
double_foo = foo * 2 # Do something to create whatever output you need
return double_foo
def function1(bar):
foobar = function2(bar) # Note that the foo and bar variables here are locally scoped
return foobar
def main():
user_input = input("Please enter your string here: ")
output = function1(user_input)
return output
main()
有关范围界定的更多信息,请查看https://matthew-brett.github.io/teaching/global_scope.html