How to call another function (temperature) as main function - python

I was typing a sample code. Where I defined temperature as the main function, but I was unable to run it. It closed automatically without any input prompt.
def temperature():
number = input('Enter what you want\n')
values = number.split(' ')
temperature = values[0]
unitin = values[1]
unitout = values[-1]
print(temperature, 'this', unitin, 'is', unitout, 'working') # this is working is a test statemment i was unsure
print('This is a test function', number)
def main():
temperature()
if __name__ == "__main__":
main()
this is the part of the code that ran. But as soon as I tried to change just the name of the main function it stopped working. I am not sure, does it only take the name "main"?
def readinput():
input_string = input('Enter what you want\n')
values = input_string.split(' ')
temperature = values[0]
unitin = values[1]
unitout = values[-1]
print(temperature, 'this', unitin, 'is', unitout, 'working')
print('This is a test function', input_string)
def temperature_converter():
readinput()
if __name__ == "__temperature_converter__":
temperature_converter()
This is the code that did not work. thank you.

If you run your code on its own, the variable __name__ is automatically set to "__main__" by the interpreter. That does not have anything to do with your functions name. Have a look at What does if __name__ == "__main__": do?
This should work:
if __name__ == "__main__":
temperature_converter()

You're confusing the contents of the special variable __name__ that contains string '__main__' in case when the module is run by itself (as opposed to imported by another module) with the function main() -- these are totally unrelated things, and when you change the name of the function main() to whatever else you like, leave the string __main__ alone, as it is.
Or you may remove the line starting with if __name__ == completely, it should work without is as well.

Related

Problem with accessing variable from function in another file

I need to get a variable declared in a function in another file.
Requirement is that I can't call the variable from setvar() function.
set.py:
def setvar():
global x
x = 100
def getvar():
return x
if __name__ == '__main__':
setvar()
getvar()
get.py:
import set
y = set.getvar()
print(y)
Error:
NameError: name 'x' is not defined
Why is x not defined? When I print it in getvar, x is defined.
How can I change it to get it work?
Why is x not defined?
The reason is because of your line:
if __name__ == '__main__':
As you know, that line means to only run the code within the if statement if the program is being run directly, rather than being imported into another program. As you are only importing the set.py program into the get.py program, the setvar() function never got called, hence the x variable never got defined.
Requirement is that I can't call the variable from setvar function.
That's not a problem! All you'll need to do is call the setvar() function outside of the if __name__ == '__main__': block once, and the problem would be fixed:
set.py:
def setvar():
global x
x = 100
def getvar():
return x
setvar()
if __name__ == '__main__':
getvar()
get.py:
import set
y = set.getvar()
print(y)
Output:
100

missing one required positional argument

I was working on a blockchain project. Nothing wrong seemed to come of it, until I added the mining function. Then it spit out two errors that it was missing positional argument. the first was the main function on line 45, and the second one was that if name is main function. which makes since. It had to do with the mining function. The code is a bit lengthy and hard to understand so I am keeping the necessary parts.
from hashlib import sha3_512
##some hashing stuff
class Block():
## the variables thrown into the function
def __init__(self, txdata, number):
#initialize function.
# More hashing stuff
class blockchain:
difficulty = 4
def __init__(self, chain=[]):
#Initialize function. Sets up the blockchain
def add(self,Block):
#lables adding stuff to the chain
def mine(self,Block):
try:
block.prev = self.chain[-1].get('hash')
except IndexError:
pass
while True:
if Block.hash()[:blockchain.difficulty] == "0"*blockchain.difficulty:
self.add(Block)
break
else:
Block.nonce +=1
def main():
blockchain()
bchain = ["Nice day stack overflow", "Once again I need help with my bad code"]
Num = 0
for txdata in bchain:
Num += 1
blockchain.mine(Block(Block.txdata, Num)) #the error popped up here. I don't get it. I tried fiddling around with it, nothing.
if __name__ == '__main__':
main()
Can you help me solve this error. It could ruin the entire project if not fixed.
Error
Traceback(most recent call last)
File "blockchain.py", line 47 in <module>
main()
File "blockchain.py", line 45, in main()
blockchain.mine(Block(Block.txdata, Num))
Type error: mine missing one positional argument: Block
You need to keep hold of the instance of blockchain().
def main():
b = blockchain() # keep hold of the instance in b
bchain = ["Nice day stack overflow", "Once again I need help with my bad code"]
Num = 0
for txdata in bchain:
Num += 1
b.mine(Block(Block.txdata, Num)) # Use the instance here
if __name__ == '__main__':
main()

define a variable used in a function in another file python

I have two files and for some reason I do not want to define my variable as an input in my function:
function.py
def test():
print(var)
if __name__ == '__main__':
var = "test"
test()
call_function.py
from function import *
global var
var = "test"
test()
If I do this i get an error saying that var is not defined. How can I solve this ?
You can do something like this, but the fact that this works does not mean that it is a good thing to do, DO NOT CODE LIKE THIS.
from function import *
var = ['I WILL FIRE YOU IF I SEE CODE LIKE THIS IN AN APPLICATION']
test.__globals__['var'] = var
test() # output: ['I WILL FIRE YOU IF I SEE CODE LIKE THIS IN AN APPLICATION']
var[0] = "DO NOT DO THIS, YOU'LL BREAK SOMETHING IF YOU DON'T KNOW WHAT ARE YOU DOING"
test() # output: ["DO NOT DO THIS, YOU'LL BREAK SOMETHING IF YOU DON'T KNOW WHAT ARE YOU DOING"]

ValuError using import function in class

I'm sure there's a simple explanation for this (beyond just that I'm new to Python), but let's say I have two file in the same directory. One is this little script in a file named lexicon.py that checks user input:
def string_checker3(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
def Chipcar_testgreeting(action):
action_split = action.split()
for i in action_split:
strcheck = string_checker3(action)
if strcheck == None:
StartGame
else:
pass
The other script, my main script, is called newGame.py and has a class like this, within which I would like to call the Chipcar_testgreeting(action) function.
from lexicon import *
class ChipCar(Scene):
def enter(self):
print "What's up mothafucka! Get in the Bran Muffin car!"
action = raw_input("> ")
user_test = lexicon.Chipcar_testgreeting(action)
user_test
if(action == "shut up chip" or action == "oh no, it's chip"):
print "forget you!"
print action
return next_scene('Your_death')
#return 'Death'
elif(action == "hi chip" or action == "hello chip"):
print "What's up?!?! Let's go to O&A..."
return next_scene('Chip_in_studio')
else:
print "what's wrong with ya are ya stupid or sumptin? Let's go to my mudda's house, I think Lamar's there..."
return next_scene('Chip_mom_house')
FirstScene = ChipCar()
StartGame = FirstScene.enter()
However, I get this error now:
user_test = lexicon.Chipcar_testgreeting(action)
NameError: global name 'lexicon' is not defined
What am I doing wrong?
As you wrote from lexicon import *, all the importable names from that module are available to you directly (in other words, you don't need lexicon. anymore).
If you write import lexicon, now you have only imported the lexicon name into your module, and you need to use it and the scope-resolution operator (that's the .) to get to the other names of objects inside that module. In this case, you can use lexicon.Chipcar_testgreeting(action).
So, either replace from lexicon import * with import lexicon, or change lexicon.Chipcar_testgreeting(action) to Chipchar_testgreeting(action).
The recommended option is to use import lexicon.
Once you sort that out, you need to resolve another major issue which is this:
if strcheck == None:
StartGame
else:
pass
Not sure what do you expect StartGame to do here, since there is nothing with this name in the lexicon.py module.

Python: Problem with if statement

I have problem with a if statement code below:
do_blast(x):
test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')
if test_empty.read() == '':
test_empty.close()
return 'FAIL_NO_RESULTS'
else:
do_something
def return_blast(job_ID):
if job_ID == 'FAIL_NO_RESULTS':
return '<p>Sorry no results :( boooo</p>'
else:
return open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/job_ID_%s.fasta' % (job_ID), 'r').read()
For some reason the code tries to assign "job_ID" to the fasta file in return_blast even though it should have returned "sorry no results". I also understand the file names and extensions are different i have my reasons for doing this.
The code works perfectly when the test_empty file is not empty.
I'm not sure if this is the problem, but your code isn't indented correctly (and that matters in Python). I believe this is what you were wanting:
do_blast(x):
test_empty = open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/%s.blast' % (z), 'r')
if test_empty.read() == '':
test_empty.close()
return 'FAIL_NO_RESULTS'
else:
do_something
def return_blast(job_ID):
if job_ID == 'FAIL_NO_RESULTS':
return '<p>Sorry no results :( boooo</p>'
else:
return open('/home/rv/ncbi-blast-2.2.23+/db/job_ID/job_ID_%s.fasta' % (job_ID), 'r').read()
I don't think your code would have even run though..
Maybe some simple printf style debugging will help:
def return_blast(job_ID):
print 'job_ID: ', job_ID
# ...
Then you can at least see what "job_ID" your function receives. This is crucial for trying to figure out why your if statement fails.

Categories