Why is this Python loop running one too many times [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 4 years ago.
Improve this question
i wanna create a Reverse word function, and i tried:
def reversa(str):
j=len(str)
for i in str:
j -=1
print(str[j], end="")
print(reversa("Apple"))
But it did not work.

Well there are existing functions for this already:
print("Apple"[::-1])
And:
print(''.join(reversed("Apple")))
Your code doesn't work because:
since there's no return and only print, just call like: reversa("Apple")
Also, would be nice to print() at the end, like (fixed up some stuff):
def reversa(s):
j=len(s)
for i in s:
j-=1
print(str[j], end="")
print()
print(reversa("Apple"))
Also if i where you, i would make a function like:
def reversa(s):
return ''.join([s[-i] for i in range(1,len(s)+1)])
Which could be called like:
print(reversa('Apple'))

You may want to use range to increment backwards from the largest index position
def reversal(str):
for i in range(len(str) - 1, -1, -1):
print(str[i], end="")
reversal("Apple")

The loop is not running one more time.
The thing is you are printing the function reversa (i.e. the return value of the function). Since you don't make the function return anything, None will be returned and printed after your function has ended.
You just need to call the function without print: reversa("Apple")

Related

Python: Passing argument from top-level function to embedded function [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.
Improve this question
This is a simplified example. But basically, I have function within a function. I want to pass the argument from the top-level function to the embedded function, but it doesn't work. How do I solve this?
Thank you
def Check(file_name, mh_criticalval):
test_file=file_name
def eval_value(excel_sht, excel_col, mh_value):
if excel_sht.cell(row=i, column=excel_col) > mh_value:
cell_cny_b=excel_sht.cell(
row=i,
column=excel_col
).value='OK'
eval_value(sht, 9, mh_criticalval)
Check('test.xlsm',1)
Method 1: De-Nesting
The most obvious method here is to remove the nested functions. Doing this is simple:
def eval_mh(excel_sht, excel_col, mh_value):
if excel_sht.cell(row=i, column=excel_col)>mh_value:
cell_cny_b=excel_sht.cell(row=i, column=excel_col).value='OK'
def CheckDiag(file_name, mh_criticalval):
test_file=file_name
eval_mh(sht, 9, mh_criticalval)
CheckDiag('test.xlsm',1)
All we did here was move the inner function out. However, if you still wanted them to be nested, try the following.
Method 2: Local/Global Variable Exploitation
Here, we replace all instances of mh_value with mh_criticalval
def CheckDiag(file_name, mh_criticalval):
test_file=file_name
def eval_mh(excel_sht, excel_col):
if excel_sht.cell(row=i, column=excel_col)>mh_criticalval:
cell_cny_b=excel_sht.cell(row=i, column=excel_col).value='OK'
eval_mh(sht, 9)
CheckDiag('test.xlsm',1)
Method 3: Why 2 functions?
In this method, we remove the function entirely!
def CheckDiag(file_name, mh_criticalval):
test_file=file_name
if sht.cell(row=i, column=9)>mh_criticalval:
cell_cny_b=sht.cell(row=i, column=9).value='OK'
eval_mh(sht, 9)
CheckDiag('test.xlsm',1)

Python Callback to variable on input [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 8 months ago.
Improve this question
if(input == "Karma Score"):
print("Your Karma score is {}.format(charKarma) + ".")
This may be an odd question, and I am new to python so I'm stumped.
I set myself a goal of finishing a text-based adventure game that features a 'Karma" system. It's basically a watered-down version of the Fallout series' Karma system.
I need help figuring out how to callback to a variable value when requested from the console.
A simplified version of my spaghetti code is:
if(Input == "Print Variable")
print("variable")
Thanks a bunch for your time.
Notwithstanding that it might be bad design as #juanpa.arrivillaga noted in the comments, it can be done quite easily in Python.
Python conceptually holds variables and their values in dictionaries, which you can retrieve using the built-in functions globals() or locals(). In your case globals() is probably what you want. So, you could print out the value of a variable karma like this:
print( globals()["karma"] )
Or, if I understand your intentions correctly, here is how it might look in context:
user_input = input("command$ ")
words = user_input.split()
if words[0] == "print":
var_name = words[1]
value = globals()[var_name]
print(value)
Just to be complete here: if the variable is defined in another module, either use getattr(module, var_name) or module.__dict__[var_name]. So, the following works, too:
import math
print( getattr(math, "pi") )
pritn( math.__dict__["pi"] )
The __dict__ here is basically what globals() returns for the current module.

how to skip a function call based on the true or false of if statement? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
can anyone tell me how to skip a function calling if a particular condition is true for example if r[3]=='Device': if this condition is true then the next function call must be skip, and if this condition is not true then the next function call must execute.the code will be like
the first function :
def sei1(r):
if r[4]=='Device':
print(r[1],r[2],r[3])
if r[7]=='Device':
print(r[5],r[6])
if r[7]=='list':
print(r[5],r[6])
if r[8]=='Device':
print(r[5],r[6],r[7])
if r[8]=='list':
print(r[5],r[6],r[7])
def se(r):
if r[5]=='Device':
print(r[1],r[2],r[3],r[4])
if r[8]=='Device':
print(r[6],r[7])
if r[7]=='list':
print(r[6],r[7])
if r[8]=='Device':
print(r[6],r[7],r[8])
if r[8]=='list':
print(r[6],r[7],r[8])
sei1(r)
se(r)
This are the two functions and what i need is if r[4]=='Device' is true then next function call se(r) must not execute.
i am new at python every suggestions are appreciated.
Thank you
You need to simply check as follows :
if r[3]!='Device': # function_call is a function which will only execute when r[3] is not equal to 'Device'
function_call()
OR
if r[3]=='Device':
pass
else:
function_call()
By skip do you mean not executing it? In that case, the good ol' simple if should just work fine?
if r[3] != 'Device':
func1()
print('function is executed!')
else:
print('function is NOT executed!')
if r[3]=='Device':
pass
else:
function()

Calculator Program in Ruby/Python without using any built in operators [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was recently asked this in an interview for junior dev position. I was asked to create a calculator program that can add,subtract, multiply and divide without using the built in +,-,*,/ operators. Essentially to build it from the ground up.
I had no idea how to solve this. Does anyone have any guidance on how to implement at least one of the operations? I can figure out the rest from there but really need some guidance.
I code in both python and ruby.
This is an example of addition.
class Integer
def add(int) # int is 5 in the demo
res = self # 7 in the demo
int.times{res = res.succ} # succ just adds 1
return res
end
end
# demo
p 7.add(5) # => 12
Apart from succ, the Integer class has a pred method, which subtracts 1. Really useful for building a subtract method. Multiplying is just adding multiple times, and integer division is just subtracting multiple times.
Study how Ruby's "operators" are implemented; They're methods and send can be used as an alternate way of calling them.
From the documentation:
Invokes the method identified by symbol, passing it any arguments specified....
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
From that:
1.send(:+, 1) # => 2
Learning more about that is left as an exercise for the reader.
If you really want to dive in, you could create base methods like:
class Fixnum
def add(value)
val = self
value.times do
val = val.succ
end
val
end
end
1.add(1) # => 2

How to call a function only Once 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 7 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
here I want to call web service function only once throughout the program.
how to accomplish this anybody suggest me
import sys,os
def web_service(macid):
# do something
if "__name__" = "__main__" :
web_service(macid)
This is how I would to that:
i_run_once_has_been_run = False
def i_run_once(macid):
global i_run_once_has_been_run
if i_run_once_has_been_run:
return
# do something
i_run_once_has_been_run = True
#Vaulstein's decorator function would work too, and may even be a bit more pythonic - but it seems like a bit overkill to me.
Using class,
class CallOnce(object):
called = False
def web_service(cls, macid):
if cls.called:
print "already called"
return
else:
# do stuff
print "called once"
cls.called = True
return
macid = "123"
call_once_object = CallOnce()
call_once_object.web_service(macid)
call_once_object.web_service(macid)
call_once_object.web_service(macid)
Result is,
I have no name!#sla-334:~/stack_o$ python once.py
called once
already called
already called

Categories

Resources