I have a code like this:
>>> def enterText(value):
command = input ("enter text: ")
value = command
>>> def start():
text = ""
enterText(text)
print ("you entered: "+str(text))
I have tied a lot of things but I can't seem to figure it out. I'm new to Python, can help me pass a string through functions? Thanks!
Strings in Python are immutable. You need to return the string from enterText() so you can use it within start().
>>> def enterText():
return input("enter text: ")
>>> def start():
text = enterText()
print ("you entered: " + str(text))
A given string object cannot be changed. When you call enterText(text), value will refer to the empty string object created within start().
Assigning to value then rebinds the variable, i.e. it connects the name "value" with the object referenced by the right-hand side of the assignment. An assignment to a plain variable does not modify an object.
The text variable, however, will continue to refer to the empty string until you assign to text again. But since you don't do that, it can't work.
Related
Defining a FUNCTION through which we pass a variable name and in return we get a new variable assigned with a user_inp value.
I Tried this :
def Uinp(variable):
variable = eval(input(f'Enter {variable} value : '))
return variable
#trying the function.
x.Uinp
#trying to call the function.
Uinp(x)
print(x)
But coudn't get the desired results..
I think you need this:
def Uinp(variable):
variable = eval(input(f'Enter {variable} value : '))
return variable
print(Uinp(x))
So it's worth knowing that you really should not do this. It is very unexpected and modification of the globals dict is going to lead to some very hard to debug errors for you or someone else.
HOWEVER, it's definitely possible. Modification of the globals dict is legal Python.
def my_function(var_name):
"""Please don't use this function it's actually Pandora's Box of bugs."""
user_inp = input("Enter some value: ")
globals()[var_name] = user_inp
Use it with:
>>> my_function("this_is_a_new_variable")
Enter some value: this is my value that I've entered
>>> print(this_is_a_new_variable)
this is my value that I've entered
I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?
string = "Hello"
reverse = string[::-1]
print(reverse)
I tried putting it in a function but I cannot make it print Hello.
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
also tried this
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
Nothing seems to work. I'm having same problem with this as well.
total = 0
def length(words):
for i in words:
total += 1
return total
Functions without a return value
Functions that just take action or do something without returning a value (for example, print).
Functions that don't return a value can be defined like that:
def sayHello():
print "Hello!"
And can be used (called) like that:
sayHello()
And the output will be:
Hello!
Function parameters
A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example.
A function that receives a name and greets this name:
def sayHelloTo(name):
print "Hello", name
It can be called like that:
sayHelloTo("Yotam")
And the output will be:
Hello Yotam
The parameters are the function's input.
Functions with a return value
Other functions, unlike sayHello() or sayHelloTo(name) (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6).
from random import randint
def rollDice():
result = randint(1, 6)
return result
The return keyword just sets the output value of the function and exits the function. An example use of the rollDice function will be:
dice = rollDice()
print "The dice says", dice
When the function hits a return keyword, it finishes and the return value (in our case, the variable result) will be placed instead of the function call. Let's assume randint(1, 6) has produced the number 3.
Result becomes 3.
Result is returned.
Now, instead of the line:
dice = rollDice()
We can treat the line as:
dice = 3
(rollDice() was replaced with 3)
Functions with parameters and a return value
Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one.
def max(a,b):
if a > b:
return a
else:
return b
What it does is pretty clear, isn't it? If a is greater, it returns the value of it. Otherwise, returns the value of b.
It can be used like that:
print max(4, 6)
And the output will be:
6
Now, your case
What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that:
def reverse_a_string(my_text):
return my_text[::-1]
now you can do something like that:
s = raw_input("Please enter a string to be reversed\n") #input in Python3
r = reverse_a_string(s)
print r
r will contain the reversed value of s, and will be printed.
About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one.
Local variables
About your 3rd example:
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
This is something that is really worth delaying and understanding.
the variable reverse is first used inside the function. This makes it a local variable.
This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done.
This means that even if you called reverse_a_string(string), you wouln't be able to use the reverse variable outside of the function, because it would be local.
If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the global keyword, like that:
reverse = "" #This makes reverse a global variable
def reverse_a_string(string):
global reverse #Stating that we are going to use the global variable reverse
reverse = string[::-1]
# Then you can call it like that:
reverse_a_string("Hello")
print reverse
The output will be
olleH
Although it's strongly not recommended to do it in Python, or in any other language.
Once you create a function you must call it. You have created the function reverse_a_string but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do something, it never will. In order for the set of instructions to happen we need to push the button (or in our case call the function). So in order for your code to work you first need to define the function then actually call it:
def reverse_a_string():
string="Hello"
reverse = string[::-1]
print reverse
reverse_a_string()
Result: 'olleH'
If you want to pass your own string in to the function so it doesn't just return 'olleH' all the time your code needs to look like such:
def reverse_a_string(stringThatWillBeReversed):
reverse = stringThatWillBeReversed[::-1]
print reverse
reverse_a_string('whateverStringYouWant')
Result: The reverse of the string you entered.
Hope that helps!
I don't know whether you are asking how to define functions in python or something else
If you want to learn python functions, go to http://www.tutorialspoint.com/python/python_functions.htm or just write python tutorial in google, you will get billions of good sites
def reverse_a_string(string):
#function definition
reverse = string[::-1]
print(reverse)
#function call
reverse_a_string("your string")
But you to define function for this, you could simply do
print( string[::-1] )
# defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply calls the function
for functions, you have to define the function, then simply call it with the function name i.e. funtion()
In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.
i am making a python script that talks back to just for fun and i want it to pick a random subject to talk about each time here is a snippet of my code
def randsub():
rand = random.randrange(1,3)
rand.toString()
randsub = "sub" + rand
randsub()
but it keeps giveing me this error
TypeError: Can't convert 'int' object to str implicitly
Put the functions in a list, then use the random.choice() function to pick one at random for you. Functions are just objects, just like any other value in Python:
import random
def sub_hello():
print('Well, hello there!')
def sub_nice_weather():
print("Nice weather, isn't it?")
def sub_sports():
print('What about them Broncos, eh?')
chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()
You got your specific error because you tried to concatenate an integer with a string ("sub" is a string, rand an integer); you'd normally convert the integer to a string first, or use a string template that supports converting other objects to strings for you (like str.format() or str % (values,)). But the string doesn't turn into a function, even if the string value was the same as a function name you happen to have defined.
I have a question here which is based around user input to scripts and passing this user-input to functions.
I have a script, within which I have defined a function. What I want the script to do is take user input to pass as arguments to the function. However, one of the things I want to pass to the function is the name of an argument rather than the argument itself. The user has the choice of using a variety of different lists to input to the function, and what I wanted was to get the user to input the name of the variable that they want to use.
Say I want to pass the argument Tablelist3 to the function. When I ask for the user input, and they input Tablelist3, what is being passed to the function is 'Tablelist3' as a string, rather than the variable itself.
How do I get it so that whichever variable the user names is the variable which gets passed to the function?
Hope my question makes sense and isn't too simple. I'm relatively inexperienced with Python.
Use a dictionary, mapping strings to objects:
tbl1, tbl2 = [1 ,2 ,3], [4 ,5 ,6]
args = {'tbl1': tbl1 ,"tbl2" :tbl2}
# show tables ......
inp = input("Choose table")
def foo(var):
print(var)
foo(args[inp])
You will want to do error checking to make sure the user actually enters something valid.
I think you can take advantage of python's global() or locals() feature.
here's an example:
from random import choice as rc
def your_function(variable):
if variable in local_keys:
print(variable, " = ", local_variables[variable])
else:
print("Your input is not a defined variable")
return
#randomly populate the variables
item1 = rc(range(20))
item2 = rc(range(20))
item3 = rc(range(20))
item4 = rc(range(20))
item5 = rc(range(20))
item5 = rc(range(20))
user_variable = input("Input the variable name: ")
local_variables = locals() # you may have to use globals instead
local_keys = list(local_variables.keys())
your_function(user_variable)
with raw_input the input is just a string
table2 = range(3)
variable_name = raw_input('Enter Variable Name: ')
def function(list_object):
print list_object
function(globals()[variable_name])
with input() the input data given by the user is evaluated, be sure that the all the possible input lists are declared before asking for user input, other wise you end up getting an NameError
table2 = range(3)
variable_name = input('Enter Variable Name: ')
def function(list_object):
print list_object
function(variable_name)
globals() function returns a dictionary of all the objects defined in the module.
you can get the respective object by passing the variable name as a key.
I have a python 3 function that takes a string of commands, say 'np.pi' and then tries to define a variable with that string. Then I try to return the variable, this however does not work.
input = np.pi
astring = 'funcD(funcC(funcB(funcA(input))))'
def function(astring):
astring= 'variable = ' + astring
exec(astring)
return variable
In: a = function(astring)
Out: NameError: global name 'variable' is not defined
Nothing seems to have happened. What I would like is to have the function return the output of the command in the string. The string contains several functions who have each other as input like below. I tried putting the exec after return without adding the variable = and then call the function with a = function(astring) but that did not work either. I believe I cant use eval because my string has functions in it.
You didn't state what you expected from the answer, so I take a guess: You want to make this work.
Try it using eval:
def function(astring):
astring= 'variable = ' + astring
exec(astring)
return eval('variable')
function('42')
returns as expected 42.
Or simply strip that assignment:
def function(astring):
return eval(astring)