Call a function from within another function in Python without using class - python

I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.
Here's an example:
Make a function shout(word) that accepts a string and returns that string in capital letters.
def shout(word):
return word.upper()
shout("bob")
Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.
def introduce():
name = input("What's your name: ")
print(f"Hello {name}")
introduce()
My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:
What's your name?
Bob
HELLO BOB
Thank you for your time and answers.

Just call function shout.
def shout(word):
return word.upper()
def introduce():
name = input("What's your name: ")
name = shout(name)
print(f"Hello {name}")
introduce()

You call functions from inside other functions the same way you call them from outside functions. Put the function name first, put the argument(s) in parentheses.
def introduce():
name = input("What's your name: ")
print(shout(f"Hello {name}"))

You can just call shout() function inside introduce():
def shout(word):
return word.upper()
def introduce():
name = input("What's your name: ")
print(shout(f"Hello {name}")) << just like this.

Related

How to accept user input from within a function?

I am new to Python. This code snippet is supposed to define a function getinput(), which is supposed to accept user input and put that value into variable stuff. Then I call the function, and print the value of the variable stuff.
def getinput():
stuff = input("Please enter something.")
getinput()
print(stuff)
The problem is that the program is not working as expected and I get the error:
NameError: name 'stuff' is not defined
In contrast, without defining and calling a function, this code works just fine:
stuff = input("Please enter something.")
print(stuff)
And I can't figure out why that should be so.
Please help. I am learning Python to coach my kid through his school course, and I am using Google Colab with Python 3.7.11, I believe.
Variables defined within a function are local in scope to that function, however, you can return values from functions so you can do what you want like this:
def getinput():
sth = input("Please enter something.")
return sth
stuff = getinput()
print(stuff)
There is a lot of possibilities of printing stuff that you could do -
def getinput():
stuff = input("Please enter something.")
print(stuff)
getinput()
You can print it inside function and call it
def getinput():
stuff = input("Please enter something.")
return stuff
print(getinput())
You can return the stuff and print it (BEST Solution)
def getinput():
global stuff
stuff = input("Please enter something.")
getinput()
print(stuff)
Or you could use global keyword
In Python, there is a concept of the scope of a variable. You create a stuff variable inside a function and the variable can only be used there. There is no such variable outside the function. You can do this:
def getinput():
getinput.stuff = input('Please enter something')
getinput()
print(getinput.stuff)
Or you can return value from function:
def getinput():
stuff = input('Please enter something')
return stuff
s = getinput()
print(s)

Autocorrect python library throwing error instead of correcting the word

I'm not really sure why this autocorrect isnt working, but every time i try to use the Speller() function i get this error:
TypeError: '>' not supported between instances of 'str' and 'int'
and here is my code:
import time
from autocorrect import Speller
def main(consoleMode):
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if Speller(inputVar.lower()) == "hi" or Speller(inputVar.lower()) == "hello" or Speller(inputVar.lower()) == "wassup" or Speller(inputVar.lower()) == "sup":
if name == None:
name = int(input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> "))
if ("not" in Speller(name) and "tell" in Speller(name)) or ("not" in Speller(name) and "say" in Speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
edit: I also tried doing int(disisastringvariable) but it just doesnt even work as it also throws an error
you might want to check out the documentation for the autocorrect module the speller class inits signature is def __init__(self, threshold=0, lang='en'): So when creating an instance of the class and passing in a single argument it will assume you are passing in a threshold.
So calling Speller("something") will pass a string in that will be stored as the threshold. then on line 27 of the init method. if threshold > 0 this string will be compared to an int. Hence the error. Since you cannot do > between a string and an int.
I would suggest first read any documentation for this module. The example from the documenation suggest to use it like
>>> spell = Speller(lang='en')
>>> spell("I'm not sleapy and tehre is no place I'm giong to.")
"I'm not sleepy and there is no place I'm going to."
You are trying to pass the code you want to check to the Speller constructor.
Instead, you should create the object once, and then it is callable and checks input. Read the examples here: https://github.com/fsondej/autocorrect
import time
from autocorrect import Speller
my_speller = Speller(lang='en')
name = None
def main(consoleMode):
global name
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if my_speller(inputVar.lower()) == "hi" or my_speller(inputVar.lower()) == "hello" or my_speller(inputVar.lower()) == "wassup" or my_speller(inputVar.lower()) == "sup":
if name == None:
name = input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> ")
if ("not" in my_speller(name) and "tell" in my_speller(name)) or ("not" in my_speller(name) and "say" in my_speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
You also had a problem with the variable name being used before declaration - I think you want to have a global instance of this and use it in all calls to your main function.

Python Function Errors

I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))

keeping changed data global variables

I have a global variable that I change in a function but when I call the global variable later in code in a different function, it doesn't store the change when the variable is first called:
name = "noname"
def username():
print ("It would help if I had a name to go by, please enter a name.")
global name
name = input()
def character():
global name
print ("Character overview:\nName:"+name+"")
And the output of character() is noname instead of the input.
Is there a way keeping the change in the first function?
This works for me.
name = "noname"
def user():
global name
name = input()
def char():
# Works with or without global here
print(name)
user()
char()

Same Variable in different Functions. (Python)

Newbie here, I am currently writing a "game" in ex 36 of LearnPythonTheHardWay.
If I wanted to ask for the user's name in one function. How can I recall that persons name in all the other functions without asking for it again, or setting it = to the name again? From my understanding variables in a function don't affect other functions, but what if I want it to?
def room_1():
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
Two ways, first would be to create a class and set an attribute called playername. Something like:
class Game(object):
def __init__(self,playername=None):
if playername is None: self.playername = raw_input("What's your name? ")
else: self.playername = playername
# initialize any other variables here
def run(self):
# all your code goes here, and self.playername
# is always your player's name.
game = Game()
game.run()
The other was is widely (and properly!) frowned upon. You could use a global
global name
name = raw_input("What is your name? ")
Now so long as you don't overwrite name in any of your functions, they can call name and access it as if it were a local variable.
EDIT: It looks like you're trying to build a game that should implement a Finite State Machine which is almost certainly beyond your ability to make right now. You can CERTAINLY do it without one, but the code will always have that "spaghetti" feel to it. class Game is the first step towards the FSM, but there's a long way to go :)
You should declare it as global when asking for the name, so it is available in other functions:
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
For now you can define a variable outside of a function, then call it with the global keyword.
Normally you would use a class for this sort of thing, but you'll get there eventually :o)
name = ''
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
global name
print "Hi %s" % name

Categories

Resources