This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
When I run the following code, it skips to the end and simply prints "Thanks for playing!"
I'm sure it's something super obvious that I've missed, any ideas? I am using Python 2.7.6.
Thanks.
import random
def roll (sides = 6):
numberRolled = random.randint(1,sides)
return numberRolled
def main():
sides = 6
rolling = True
while rolling:
roll_again = raw_input("Press Enter to roll, or Q to quit.")
if roll_again.lower() != "q":
numberRolled = roll(sides)
print ("You rolled a " + numberRolled)
else:
rolling = False
print ("Thanks for playing!")
Python in itself has no concept of a main method. When it reads your code, it imports random, defines a method named roll, defines another method named main, then prints "Thanks for playing". It does nothing else, unless you tell it to
If you want to call main(), you'll need to do this yourself. Traditionally (to work with other code that might want to import yours as a module), it would look like this:
import random
def roll():
...
def main():
...
if __name__ == '__main__':
main()
print("Thanks for playing")
That will check if the module name is __main__ (which is true for the main script) and call your main method
You need to add if __name__ == '__main__:', and call main() from there:
import random
def roll (sides = 6):
numberRolled = random.randint(1,sides)
return numberRolled
def main():
sides = 6
rolling = True
while rolling:
roll_again = raw_input("Press Enter to roll, or Q to quit.")
if roll_again.lower() != "q":
numberRolled = roll(sides)
print ("You rolled a " + numberRolled)
else:
rolling = False
if __name__ == '__main__':
main()
print ("Thanks for playing!")
For details as to why and how it works, please see:
- what-does-if-name-main-do
- tutorial name == main
- python documentation
You need to run main
if __name__ == "__main__":
main()
Related
I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()
I am new and trying to create a simple "guess the number game":
import random
class Randgame :
def __init__(self):
pass
def restart(self):
response = input("Type Yes To Play Again!").lower()
if response == "yes":
self.play()
else:
print("Thanks for playing!")
pass
def play(self):
guess = int(input("What's your guess?"))
num = random.randint(0, 10)
if guess == num:
print("Correct!")
else:
print("Nope!")
self.restart()
fun = Randgame()
fun.play()
All is well until I get to the restart() method. If I type "yes" into the console I get this response:
NameError: name 'yes' is not defined
I cannot figure this out to save my life and I don't know what to look up. Please help!
In Python 2, getting input as plain text is done via raw_input instead of input. Python 3 changed the name of the function to input. The Python 2 version of input does eval(raw_input(prompt)), so it is trying to actually access a variable called yes, when you just want to get the string "yes".
Python 2 Docs
So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.
This question already has answers here:
Python, unable to convert input() to int()
(3 answers)
Closed 3 years ago.
I'm trying to do a menu, it's so easy but I don't understand why never ends my loop, I attach my code:
def main():
menu_bool = False
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Why when I press "1" ask me again to choose an option? I have declared a boolean variable for stop it, menu_bool = True, but I don't know why my main function is in loop.
I try it doing a global variable but it don't works too. Then this means that my menu_bool = True is never done but I don't understand why.
menu_bool = False
def main():
global menu_bool
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Thank you so much!
As others have said, basically you are comparing strings with ints. Also I'd suggest being a bit more pythony with bools, in this case using not instead of comparing explicitly via comparison operator.
def main():
menu_bool = False
while(not menu_bool):
print("Menu:\n\t1. Copiar")
x = input()
if x == '1':
print("You have selected option 1.")
menu_bool = True
Hello i have been working on this simple script and i have run into some rather annoying problems that i can not fix myself with the def. and import function it just won't work. here is the main script
import time # This part import the time module
import script2 # This part imports the second script
def main():
print("This program is a calaulater have fun using it")
name = input("What is your name? ")
print("Hello",name)
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
script2 test()
if q1 == "no":
print("That is fine",name,"Hope to see you soon bye")
time.sleep(2)
if __name__ == '__main__':
try:
main()
except Exception as e:
time.sleep(10)
And then the second script is called script2 here is that script as well
import time
def test():
print("You would like to do some maths i hear.")
print("you have some truely wonderfull option please chooice form the list below.")
That is my script currently but it deos not work please help me.
Firstly your indentation doesn't seems to be right. As zvone stated. Secondly you should use script2.test() instead of script2 test(). A functional code is
import time # This part import the time module
import script2 # This part imports the second script
def main():
print("This program is a calaulater have fun using it")
name = input("What is your name? ")
print("Hello",name)
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
script2.test()
if q1 == "no":
print("That is fine",name,"Hope to see you soon bye")
time.sleep(2)
if __name__ == '__main__':
try:
main()
except Exception as e:
time.sleep(10)
This is an error:
def main():
#...
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
# ...
Firstly, the q1 in main() and the q1 outside are not the same variable.
Secondly, if q1 == "yes": is executed before q1 = input(...), because main() was not called yet.
The solution would be to return the q1 value from main and only then use it:
def main():
# ...
return q1
if __name__ == '__main__':
# ...
result_from_main = main()
if result_from_main == "yes":
# ...
Of course, the all names are completely messed up now, but that is a different problem...