How do I access the string inside my function python? - python

Trying to gain access to this string to test it if it has 3 or more blues "b" inside of it. ---Both test and three_or_more_blues are functions.----- I'm completely lost, any one got an idea? Please change my title if it doesn't fit my question. Not sure really how to ask the question. Thanks!
test(three_or_more_blues, "brrrrrbrrrrrb")

Assuming test is a function that takes a function and a string as paramters, and three_or_more_blues is a function that returns true if its string parameter has 3 or more 'b' characters, then
def test(func, str):
if func(str):
# do something with str
test(three_or_more_blues, "brrrrrbrrrrrb")

You could use .count().
sentence = 'brrrrrbrrrrrb'
amount = sentence.count('b')
print(amount)
And then you could use a loop to calculate your next step.
if (amount >= 3):
# Do something

I am not sure if I understand you correctly - you are asking how to pass the string 'brrrrrbrrrrrb' to the three_or_more_blues function?
If that is the case, than you just simply pass it when you call the three_or_more_blues function like this:
def test(func, some_string):
func(some_string) # here you call the passed function
# if three_or_more_blues would look like this:
def three_or_more_blues(some_string):
print "Yes, 3 or more b's" if some_string.count('b') >= 0 else "No"
# you would get this from your function call
test(three_or_more_blues, "brrrrrbrrrrrb") # prints: "Yes, 3 or more b's"

Related

How to store formula,in function, as string to output later?

I am trying to create a function in which I will store formulas for my converter. When X formula will be needed, it will be called from it. When trying it with simple 0:a+b it works when returning, but when trying to store it as string meters_to_foots, it doesn't work. I need to have that formula stored as something since I need to output it later.Here is a part of the code which I have problems with. NameError: name 'meters_input' is not defined
def my_formulas(i):
switcher={
0:(meters_input/0.3048)
}
return switcher.get(i,"Invalid formula")
distance_pick=input("Please pick one of the current convertions : \n \n1.Meters to X \n2.Inches to X \n3.Feets to X ")
if(distance_pick=="1"):
cls()
distance_choice = input ("Please select which converter would you like to use ! : \n \n1.Meter to Foot \n2.Meter to Yard \n3.Meters to Inches ")
if(distance_choice=="1"):
meters_input=float(input("Make sure to enter distance in Meters ! : "))
my_formulas(0)
print ("\nYou entered", meters_input , "meters, which is equal to",my_formulas(0),"foots.")
time.sleep (3)
cls ()
read_carefully_message()
To create a function in Python use either lambda functions or the regular function definition. Examples are respectively:
def divide(meters_input):
return meters_input / 0.3048
or
divide = lambda meters_input: meters_input / 0.3048
Generally the regular function definition is preferred since it improves readability. You can define your function mapping as follows:
def my_formulas(i):
switcher={
0:divide # do not write divide()
}
If these will always be simple functions you can use a lambda expression for this:
def my_formulas(i):
switcher= {
0:lambda meters_input: meters_input/0.3048
}
return switcher.get(i,"Invalid formula")
my_formulas(0)(27) #88.58267716535433
If your function lookup will always be a number starting with zero you might be better off storing the functions as an array. You could do something like this as well:
def my_formulas(index):
def meters2Feet(meters):
return meters/0.3048
def hours2Minutes(hours):
return hours * 60
def invalid(*args):
return "Invalid formula"
lookup = [
meters2Feet,
meters2Feet
]
if index >= len(lookup):
return invalid
return lookup[index]
my_formulas(0)(27) # 88.58267716535433
It's a little more complicated, but probably easier to read and understand.
Try changing your function to this:
def my_formulas(i):
switcher = (i/0.3048)
return switcher
The "i" in the function is a local variable for the function. In your code you are passing 0 into the my_formulas() function. i then becomes 0, but meters_input is out of scope for the function.

Calling the result of a function in another function

The code is very long so I won't type it in.
What I am confused about as a beginner programmer, is function calling. So I had a csv file that the function divided all the content (they were integers) by 95 to get the normalised scores.
I finished the function by returning the result. its called return sudentp_file
Now I want to continue this new variable into another function.
So this new function will get the average of the studentp_file. So I made a new function. Ill add the other function as a template of what im doing.
def normalise(student_file, units_file)
~ Do stuff here ~
return studentp_file
def mean(studentp_file):
mean()
What I get confused about is what to put in the mean(). Do I keep it or remove it? I understand you guys don't know the file I'm working with my a little basic understanding of how functions and function calling works would be appreciated. Thanks.
When you call your function you need to pass in the parameters it needs (based on what you specified in your def statement. So you code might look like this:
def normalise(student_file, units_file)
~ Do stuff here ~
return studentp_file
def mean(studentp_file):
~ other stuff here ~
return mean
# main code starts here
# get student file and units file from somewhere, I'll call them files A and B. Get the resulting studentp file back from the function call and store it in variable C.
C = normalize(A, B)
# now call the mean function using the file we got back from normalize and capture the result in variable my_mean
my_mean = mean(C)
print(my_mean)
i assume that normalise function is executed prior to mean function? if so try out this structure:
def normalise(student_file, units_file):
#do stuff here
return studentp_file
def mean(studentp_file):
#do stuff here
sp_file = normalise(student_file, units_file)
mean(sp_file)
functions in python(2/3) are made for reusability and to keep your code organized in a block. these functions may or may not return a value, based on arguments you pass (if it accepts arguments). think of it as if functions are like real life factories making finished products. raw goods are fed into factories, so that they produce a finished product. functions are also like that. :)
now, notice that i assigned a variable called sp_file with the value of the function call normalise(...). this function call - accepted parameters (student_file, units_file) - which are your 'raw' goods to be fed towards your function normalise.
return - basically returns whatever value towards the point in your code which called your function. in this case return, returns the value of studentp_file back to sp_file. sp_file would then get studentp_file's value and can be then passed to mean() function.
/ogs
Well, it's unclear buy why not just (dummy example):
def f(a,b):
return f2(3)+a+b
def f2(c):
return c+1
Call the f2 in f and do return in f2
If the results from function one will always be called to function two you could do this.
def f_one(x, y):
return (f_two(x, y))
def f_two(x, y):
return x + y
print(f_one(1, 1))
2
Or just a thought... You could set up a variable z that works as a switch, if its 1 it passes the result to function to the next function , or if 2 returns result of function one
def f_one(x, y, z):
result = x + y
if z == 1:
return (f_two(result))
elif z == 2:
return result
def f_two(x):
return x - 1
a = f_one(1, 1, 1)
print(a)
b = f_one(1, 1, 2)
print(b)

Python - why isnt my function outputting 'a' ten times? Beginner question

def testfunction():
for i in range(10):
return('a')
print(testfunction())
I want 'a' outputed 10 times in one line. If I use print instead of return, it gives me 10 'a's but each on a new line. Can you help?
return terminates the current function, while print is a call to another function(atleast in python 3)
Any code after a return statement will not be run.
Python's way of printing 10 a's would be:
print('a' * 10)
In your case it would look like the following:
def testfunction ():
return 'a' * 10
print(testfunction ())
The reason its only printing once is because the return statment finishes the function (the return function stops the loop).
In order to print 'a' 10 times you want to do the following:
def testfunction():
for i in range(10):
print('a')
testfunction()
If you want "a" printed 10 times in one single line then you can simply go for:
def TestCode():
print("a"*10)
There's no need to use the for loop. For loop will just "a" for 10 times but every time it'll be a new line.
You can also take in a function argument and get "a" printed as many times as desired.
Such as:
def TestCode(times):
t = "a"*times
print(t)
Test:
TestCode(5)
>>> aaaaa
TestCode(7)
>>> aaaaaaa
print and return get mixed up when starting Python.
A function can return anything but it doesn't mean that the value will be printed for you to see. A function can even return another function (it's called functional programming).
The function below is adapted from your question and it returns a string object. When you call the function, it returns the string object into the variable called x. That contains all of the info you wanted and you can print that to the console.
You could have also used yield or print in your for loop but that may be outside of the scope.
def test_function(item:str="a", n:int=10):
line = item*n # this will be a string object
return line
ten_a_letters = test_function()
print(ten_a_letters)
"aaaaaaaaaa"
two_b_letters = test_function("b",2)
print(two_b_letters)
"bb"
I want 'a' outputed 10 times in one line. If I use print instead of
return, it gives me 10 'a's but each on a new line.
If you want to use print, the you need to pass a 2nd parameter as follows:
def testfunction():
for i in range(10):
print('a', end='')
However, I think the pythonic way would be to do the following:
def testfunction():
print('a' * 10)
When you use return you end the execution of the function immediately and only one value is returned.
Other answers here provide an easier way to solve your problem (which is great), but I would like to suggest a different approach using yield (instead of return) and create a generator (which might be an overkill but a valid alternative nonetheless):
def testfunction():
for i in range(10):
yield('a')
print(''.join(x for x in testfunction()))
1. What does "yield" keyword do?
def test ():
print('a' * 10)
test()
Output will be 'aaaaaaaaaa'.

Python Parameter passing for another function

I have created two functions namely inputData(): and validateNumber():
In the inputData() function I enter a value and stores it in a variable called number. And then I want to pass that parameter to validateNumber(): function. But it isn't work :(
It would be fine if anyone explain me the error :)
Regards.
Here's the code:
def inputData():
number = int(input("Enter a Number: "))
print(number)
return number
def validateNumber(number):
n=2
while number > n:
if number%n==0 and n!=number:
print("Not Prime")
break
else:
print("Prime")
break
return number
inputData()
validateNumber()
You need to perform the function call as follows:
validateNumber(inputData())
or
number = inputData()
validateNumber(number)
with def validateNumber(number) you are telling python that the function validateNumber must receive one parameter when it is called. But, you are not passing the parameter to it when you call it.
If you are new to programming, check this tutorial: Python Functions, to understand:
What are functions
How to define them
How to use them.
You need to store the value of inputData() function in some variable then pass it to second function like this
>> number = inputData()
>> validateNumber(number)
You're not passing the inputted number to the validate function.
returned_input_number = inputData()
validateNumber(returned_input_number)
Also, I find it a bit odd that your validateNumber function returns a number. It might be better to return True or False (depending on if the number is valid or not). Either that, or maybe 'validate' is the wrong name for the function.

How to complete this function then print it out, using Python?

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.

Categories