Passing strings to functions [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I know this is a stupid question but I don't know exactly how to search for it.
I want to feed a parameter into a function to conditionally run code.
In the example below, if I specify the word single in the function call, I would like it to run the line of code at the top and return the string "This". If I specify any other word, I want it to run the second line of code and return "That".
Example:
def condfunc(myvar):
if myvar == single:
something = "This"
else:
something = "That"
return something
mysomething = condfunc(single)
I keep getting:
NameError: name 'single' is not defined

I think you are trying to test which of two strings the argument myvar is? In that case, the code should look like:
def condfunc(myvar):
if myvar == "single":
something = "This"
else:
something = "That"
return something
which can be simplified to:
def condfunc(myvar):
return "This" if myvar == "single" else "That"
and you would call it, e.g.:
test = "single"
mysomething = condfunc(test)

Related

check unreachable code in most simple way in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I have a python code with is detect any errors in another python code saved in txt file, i did that i can detect magic numbers and more than 3 parameters in the function, and now i have to check un reachable code, but i don't have an idea how can i do it, i want to detect if there's a code after return in the function, i did several attempts and all of them failed
This main class :
class CodeAnalyzer:
def __init__(self, file):
self.file = file
self.file_string = ""
self.errors = {}
this is a method where it's pass detects function so i can print errors :
def process_file(self):
for i, line in enumerate(self.file):
self.file_string += line
self.check_divide_by_zero(i, line)
self.check_parameters_num(i, line)
and for example this is check parameter function, i need to write similar one but to detect unreachable code :
def check_parameters_num(self, i, line):
count = line.count(",")
if(line.startswith('def') and count+1 >= 3):
self.errors.setdefault(i, []).append(('S007', ''))
Any one can help and have an idea ?
Probably you would have to use the ast module to look at the parse tree.
Look for:
Conditions for if and while statements that are always False. (or always true in case of an else) This would involve "constant propagation", that is realizing that an expression that only depends on constants is itself constant.
Code after a return, without that return being part of an if.
Code at the end of a function that is indented incorrectly an thus in the module context.
Or you could look at how mypy is doing it.

How to use a function in if else [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
def getmessages(_,m):
coin = ""
if m.chat.id == boticindneme:
coin += m.text
return coin
if getmessages(_,m) == "something":
when I use this it gives the error _ is not defined so how can I use a function in if else
That is strange code. As a convention, python programs use _ to denote a variable that you have to put in to make a program work, but don't really need. An example is a function that returns multiple variables but you don't want them all. Suppose you wanted the second thing in a string, you could do
foo = "1,2,3"
_, bar, _ = foo.split(",", maxsplit=2)
print(bar)
Python would unpack the resulting ["1", "2", "3"] into _, then bar, then _ again. But you don't care about _ so its okay to overwrite it.
But to put it into function parameter is weird. You are requiring a parameter that you don't use. That's harsh!
When you define a function, you are creating names that the function will use for its parameters, not what outside code needs to call things.
def getmessages(_,m):
coin = ""
if m.chat.id == boticindneme:
coin += m.text
return coin
This doesn't create variables outside of the function, you need to create those yourself. Since the function doesn't actually use _, you can put anything into it. None seems like a good choice. And since we don't know what this m thing is, I'll make something up.
foo = WhateverThatMThingIs()
if getmessages(None, foo) == "something":
print('okay")

Not Match Between Argument Passed and List Available [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I was working with Python3, and trying some sorts of code. And then i came to try some function features, here is my code
def print_list_members(some_list):
for i in first_list:
print(i)
that's all my function definition. and then i add for example new to the code
first_list = ["Alfried", "Michael", "John"]
second_list = ["Joseph", "Tim", "Delta"]
then i try to produce traceback by passing different argument with the function code
print_list_members(second_list)
but, no traceback raised, except something make me a bit confused, the output is
Alfried
Michael
John
the question is, how it be possible? or is it an error from python itself?
Change your code here
def print_list_members(some_list):
for i in some_list:
print(i)
You iterate over the global first_list inside the body of the function, so you print first_list. Whatever you pass as an argument is ignored. Perhaps you wanted iterate over some_list?

How do I stub functions in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
It's my first few lessons in programming and i've encountered a question that i don't really understand how to proceed.
def defeat_balrog(protagonist):
def spawn_balrog():
"""Spawns and returns a stubborn balrog"""
pass
def balrog_attack(balrog, person):
"""Returns an attack move from the balrog's repertoire"""
pass
cave_balrog = spawn_balrog()
is_balrog_defeated = False
yell(protagonist, 'You cannot pass!')
while not is_balrog_defeated:
current_attack = balrog_attack(cave_balrog, protagonist)
if current_attack != None:
take_defensive_action(protagonist, current_attack)
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
is_balrog_defeated = True
return True
def take_defensive_action(attacked_entity, attack_move):
"""
attacked_entity anticipates attack_move and defends himself.
"""
pass
#my stubs here#
defeat_balrog('gandalf')
I'm supposed to identify the remaining functions that have been wishfully used, but for which stubs have not been created, and fill in from the last line #my stubs here#. not sure how to get started or proceed on.
A stub is a function that exists but for which no meaningful business logic has been defined. For example:
def take_defensive_action(attacked_entity, attack_move):
pass
Notice the pass statement here? It means that you've defined a valid function, but it does nothing.
Pasting your code into PyCharm, I see the following functions highlighted in "yellow" (that means those function names have an Unresolved reference):
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
Clear on the meaning of what a stub is, you should be able to define these functions accordingly as they haven't been defined yet. Here's an example for yell:
def yell(protagonist, message):
pass
I leave the second to you.

Python: Call an object from 'n string value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I sincerely hope this is not a duplicate, but I cannot find an answer (you'll notice that I don't even know how to ask the question!).
I have python code with one class and many def. It would take too much time to explain why I would want to do the following, but I sure would be able to:
class A:
def a(self):
some argument
def b(self):
another argument
So to call the def's, I just put:
A().a()
A().b()
What I would like to do is have a third def that looks like this:
def c(self):
process = [A().a(), A().b(), A().a(), A().a()] #This sequence is just an example - there are many more def's.
for i in process:
print 'Hello'
i
print 'Bye'
I don't know if this makes any sense? What happens currently is the process part is called and the two print lines are printed several times thereafter.
Thanks.
Might this work?
def c(self):
process = [self.a, self.b, self.a, self.a]
for i in process:
print 'Hello'
i()
print 'Bye'
In your original example, instead of storing the functions, you were calling them already when the list was built. The return values from your methods got stored in the list, so that is why they could not be called later.

Categories