issues importing a script - python

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...

Related

Using Python for default parameters

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()

while loop, asking user if he wants to repeat the program problem

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.

Extreme newbie - Python code skipping to the end (syntax issue?) [duplicate]

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()

global name is not defined error

My code:
import sys
import time
import random
def main():
print('***TEST**** Grad School Multiplier=',gradschoolmultiplier,'***TEST***')
x=gradschoolmultiplier*50000
print('Your salary in dollars, $',x)
def start():
gradschool=input('Do you intend to go to Graduate School? ')
print('')
time.sleep(2)
if gradschool=='yes':print('That is a fantastic if expensive decision.')
elif gradschool=='Yes':print('That is a fantastic if expensive decision.')
elif gradschool=='Y':print('That is a fantastic if expensive decision.')
elif gradschool=='y':print('That is a fantastic if expensive decision.')
elif gradschool=='YES':print('That is a fantastic if expensive decision.')
else:print('No? Well, then it\'s off to work to pay back those student loans.')
print('')
if gradschool=='yes':g1=3
elif gradschool=='Yes':g1=3
elif gradschool=='Y':g1=3
elif gradschool=='y':g1=3
elif gradschool=='YES':g1=3
else:g1=1
g=random.randrange(1, 3)
if g==1:gradschoolmultiplier=1
else:gradschoolmultiplier=g1*g/2
time.sleep(2)
main()
start()
And of course I get:
NameError: global name 'gradschoolmultiplier' is not defined
I am not smart enough to understand the answers to this question for others. Would someone be so kind as to explain the answer in simpletons' terms? Thanks!
Indeed as #Dan says, the scoping problem.
Or you can use global variables.
Some of my other suggestions on your code:
import sys
import time
import random
def print_salary():
print('***TEST**** Grad School Multiplier=',gradschoolmultiplier,'***TEST***')
x = gradschoolmultiplier*50000
print('Your salary in dollars, $',x)
def main():
gradschool=input('Do you intend to go to Graduate School? ')
print('')
time.sleep(2)
if gradschool.lower() in {'yes', 'y'}:
print('That is a fantastic if expensive decision.')
g1 = 3
else:
print('No? Well, then it\'s off to work to pay back those student loans.')
g1 = 1
print('')
g = random.randrange(1, 3)
global gradschoolmultiplier
if g == 1:
gradschoolmultiplier = 1
else:
gradschoolmultiplier = g1 * g / 2
time.sleep(2)
print_salary()
if __name__ == '__main__':
main()
You should combine some the if statements to make it simpler.
Oh, we share the same thoughts #jonrsharpe
Quick improvement as suggested by #Nils
gradschoolmultiplier is not in the scope of main(), it only exists in start().
You can pass it into main.
change the call to main to be main(gradschoolmultiplier)
change def main() to def main(gradschoolmultiplier):
Information on python scoping

Python Exit The loop and start the whole process from start once again

I am new to Python Scripting. I have written a code in python. it works pretty fine till now. What I need to know is how can I run it multiple times, I want to start the whole script from start if the condition fails. The sample code is below. This script is saved in file called adhocTest.py so I run the script like below in python shell
while 1 ==1:
execfile('adhocTest.py')
The function main() runs properly till the time txt1 == 2 which is received from the user input. Now when the input of txt1 changes to other than 2 it exits the script because I have given sys.exit() what I need to know is how can I start the the script adhocTest.py once again without exiting if the input of tx1 is not equal to 2. I tried to find the answer but somehow I am not getting the answer I want.
import time
import sys
import os
txt = input("please enter value \n")
def main():
txt1 = input("Please enter value only 2 \n")
if txt1 == 2:
print txt
print txt1
time.sleep(3)
else:
sys.exit()
if __name__ == '__main__':
while 1 == 1:
main()
You are only re-calling main in your else. You could re-factor as follows:
def main():
txt1 = input("Please enter value only 2 \n")
if txt1 == 2:
print txt
print txt1
time.sleep(3)
main()
Alternatively, just call main() (rather than wrapping it in a while loop) and move the loop inside. I would also pass txt explicitly rather than rely on scoping:
def main(txt):
while True:
txt1 = input("Please enter value only 2 \n")
if txt1 == 2:
print txt
print txt1
time.sleep(3)
The latter avoids issues with recursion.
I think this is what you want:
import time
import sys
import os
def main():
while True:
txt = input("please enter value \n")
txt1 = input("Please enter value only 2 \n")
if txt1 == 2:
print txt
print txt1
time.sleep(3)
if __name__ == '__main__':
sys.exit(main())

Categories

Resources