I am trying to get my head around python. This is a snippet of code where I want to have the user input an option in a function and then use that input in another function(s). This tells me 'myInput' is not defined.
def main():
myInput = input("Enter a number ")
# This is the main function that will be the primary executuable function - the start of the program
return(myInput)
if __name__ == '__main__':
main()
#
print (myInput)
Function main returns the user's input, so try this:
if __name__ == '__main__':
myInput = main()
Related
This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 2 years ago.
If I execute the codes below without if name == 'main', nothing is printed on the screen.
That is, if name == 'main' seems to be essential.
What is the function of if name == 'main'?
# if __name__ =='__main__':
# main()
def input_celsius_value():
value = float(input("input celsius for converting it to fahrenheit : "))
return value
def convert_celsius_fahrenheit(celsius_value):
fahrenheit_value = ((9/5)*celsius_value)+32
return fahrenheit_value
def print_fahrenheit_value(celsius_value, fahrenheit_value) :
print("celsius temperature : %f" %celsius_value)
print("fahrenheit temperature : %f" %fahrenheit_value)
def main():
print("This program converts celsius to fahrenheit")
print("============================")
celsius_value = input_celsius_value()
fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
print_fahrenheit_value(celsius_value, fahrenheit_value)
print("===========================")
print("This program ended")
if __name__ == '__main__':
main()
Without those 2 lines of code
if __name__ == '__main__':
main()
there is no function called, you just define 4 functions so nothing is executed. When the interpreter runs a source file it runs all the code in it. Even just having main() without if __name__ == '__main__': will still execute your function. __name__ is just a special variable that gets populated depending on what is being executed (the name of the class/function/method etc). When you run a new file, the interpreter initializes it to '__main__' and you can use that as an entry point for your program.
My aim:
To create a python Modules with 3 functions:
Sample input1: bob
output:
Yes it is a palindrome
No. of vowels:1
Frequency of letters:b-2,o-1
=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
ch = input("Enter a character: ")
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
In a new file I am giving :
import test
def main():
while True:
word = input("enter a word")
test.isPalindrome(word))
test.count_the_vowels(word))
if __name__ == "__main__":
main()
If I call my module in another file, it automatically does all the functions. But I want to give input(name) in this new module and check the output for it.But this is asking input again since name is present before def function in the other file. How to overcome this?
I am new to coding.Please be as elaborate as possible.Thanks in advance.
If you're question is "how to ask for the name only once and pass it to both function", the answer is simple: in your main.py script (or test.py or however you named it), add this:
import yourmodule # where you defined your functions
def main():
while True:
word = input("enter a word (ctrl+C to quit) > ")
yourmodule.isPalindrome(word)
yourmodule.count_the_vowels(word)
# etc
if __name__ == "__main__":
main()
Now note that your assignment doesn't say you have to do this - it says:
Import the module in another python script and test the functions by passing appropriate inputs.
Here, "passing appropriate inputs" can also be understood as having a harcoded list of words and calling your functions with those names... IOW, a unit test.
After trying several times to explain in the comments here is a brief example. so make a file with your functions. then in your other file import your funcs file then ask user for name and pass it to the funcs. This is just an example of how to define functions in one file and then call them from another. you probably want to look at your funcs as they should probably return values rather then just print stuff otherwise your calling file wont be able to validate the function since it will receive nothing back.
MyFuncs.py
def hello(name):
print(f"hello {name}")
def goodbye(name):
print(f"goodbye {name}")
stackoverflow.py
import MyFuncs
name = input("Name: ")
MyFuncs.hello(name)
MyFuncs.goodbye(name)
**OUTPUT: **when running the stackoverflow.py script
Name: Chris
hello Chris
goodbye Chris
Following code works as expected. It takes two inputs and outputs the same
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
if __name__ == "__main__":
main()
The moment I add this additional code for enabling more depth for recursion and threading, it throws a value error. Inputs I give are '3' for the first input (without quotes) and '-1 0 1' for the second input (without quotes).
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()
if __name__ == "__main__":
main()
The main() function is called from two places.
First, From the thread main() function will be called
threading.Thread(target=main).start()
Second, the __main__ will be called. So here also the main() function is called.
if __name__ == "__main__":
main()
So you were asked to enter the "input n" two times. While entering the string value ('-1 0 1') the second time, you are giving value to the "input n" again. It's expecting int as input. So the issue is happening.
Code Fix:
Move the thread inside main and remove the existing main()
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n, str(parents)))
if __name__ == "__main__":
sys.setrecursionlimit(10 ** 7) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
threading.Thread(target=main).start()
I hope it'll help you...
The program asked is:
"besides testing if the length of the given string is more than ten characters, it also tests if there is the character "X" (capital X) in the given string. If the string is longer than 10 characters and it has X in it, the tester subfunction returns a value True to the main function, otherwise False.
If the subfunction returns True to the main function, the program prints "X spotted!". As earlier, if the user inputs "quit", the program terminates."
This is what I tried, but the part of checking the x character does not work at all
def check(st,res="Too short"):
if len(st)>=10:
if checkX(st):
st=st+"\nX spotted!"
return st
else:
return res
def checkX(st):
for i in st:
if i=="X":
return True
return False
def main():
while True:
st=input("Write something (quit ends): ")
if st=="quit":
break
print(check(st))
It only checks if introduced string length is equal or higher than 10 characters.
The code works.
What should you change in your code:
You can use the in operator:
if "blah" not in somestring:
continue
Does Python have a string 'contains' substring method?
Do a real "main":
if __name__ == '__main__':
What you can do if you want to keep the main() function:
A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
main — Top-level script environment
Result (this code works, it is simplier, more pythonic and respect pep8):
def check_input(tested_sentence: str, result: str = "Too short"):
if len(tested_sentence) >= 10:
if "X" in tested_sentence:
result = tested_sentence + "\nX spotted!"
else:
result = tested_sentence
return result
def main():
while True:
sentence = input("Write something (quit ends): ")
if sentence == "quit":
break
print(check_input(sentence))
if __name__ == '__main__':
main()
Code Style — The Hitchhiker's Guide to Python
Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)
You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...
Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.
The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()