How do I successfully include a definition in a if function - python

How do I put a definition function into a if statement so when it's running the program will activate the definition by itself.
person=int(input("select the number of any option which you would like to execute:"))
if (person)==(1):
print ("please write the value for each class ")
main()
def main ():
juvenile=(input(" number of juveniles: "))
adult= (input(" number of adults:"))
senile=(input("number of seniles:"))
When i run it it always gives me an error.
Traceback (most recent call last):
File "C:\Users\fenis\Desktop\TEST PAGE 4 GCSE CS CW.py", line 6, in <module>
main()
NameError: name 'main' is not defined
>>>

You can't call main() at a point where main() hasn't been defined. Move your definition of main() to above the place where you try and call it.
def main():
juvenile = input("number of juveniles:")
adult = input("number of adults:")
senile = input("number of seniles:")
person = int(input("select the number of any option which you would like to execute:"))
if person==1:
print ("please write the value for each class ")
main()

Related

I was trying to use a function from a different class in the main class, but i receive this: line 15, in MainMenu chosenOption.issuing_new_ticket()

While building my project I wanted to be able to operate on different classes and objects, but when I was trying to use a function from a different class in the main class, but i receive this: line 15, in MainMenu chosenOption.issuing_new_ticket() and line 4, in class MainMenu:.
I think it is because i am not creating my second class properly, how should i work around it ?
Here is my code:
class MainMenu:
global chosenOption
global ticketTitle
global ticketDescribtion
print("Welcome to Ticket Tracker")
print("Main Menu")
print("1 - Issue new Ticket")
print("2 - Check Ticket Status")
print("3 - Edit Ticket")
print("4 - Exit")
chosenOption = input("Enter your choice here: ")
chosenOption.Options.issuing_new_ticket()
class Options:
def issuing_new_ticket(self):
if chosenOption == "1":
print("Issuing new ticket in progress")
ticket_title = input("Title of the ticket: ")
ticket_describtion = input("Describe the issue/request: ")
Firstly, Option class should be at the above of MainMenu class, otherwise it will show this error.
Traceback (most recent call last):
File "c:\Users\apned\apneMailer\demo2.py", line 73, in <module>
class MainMenu:
File "c:\Users\apned\apneMailer\demo2.py", line 84, in MainMenu
Options().issuing_new_ticket(chosenOption)
^^^^^^^
NameError: name 'Options' is not defined
Because inside MainMenu class we call Option class which was not found by the python as python runs from top to down.
Secondly, you should not write :
chosenOption.Options.issuing_new_ticket()
As Options is not a strings's class in python. And, if you do this you will get this error.
Traceback (most recent call last):
File "c:\Users\apned\apneMailer\demo2.py", line 73, in <module>
class MainMenu:
File "c:\Users\apned\apneMailer\demo2.py", line 84, in MainMenu
chosenOption.Options.issuing_new_ticket()
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'Options'
What should you do now?
Here is the working code...
class Options:
def issuing_new_ticket(self, chosenOption):
if chosenOption == "1":
print("Issuing new ticket in progress")
ticket_title = input("Title of the ticket: ")
ticket_describtion = input("Describe the issue/request: ")
class MainMenu:
global chosenOption
global ticketTitle
global ticketDescribtion
print("Welcome to Ticket Tracker")
print("Main Menu")
print("1 - Issue new Ticket")
print("2 - Check Ticket Status")
print("3 - Edit Ticket")
print("4 - Exit")
chosenOption = input("Enter your choice here: ")
Options().issuing_new_ticket(chosenOption) # calling Option's issuing_new_ticket() function
if __name__ == "__main__":
MainMenu()

Call a nested function through a global function?

I am new to Python and am trying to make a simple game with several chapters. I want you to be able to do different things depending on the chapter, but always be able to e.g. check your inventory. This is why I have tried using nested functions.
Is it possible to create a global function which acts differently depending on what chapter I am in, while still having certain options available in all chapters or should I perhaps restructure my code significantly?
I get the following error code:
> Traceback (most recent call last): File "test.py", line 21, in
> <module>
> chapter1() File "test.py", line 19, in chapter1
> standstill() File "test.py", line 4, in standstill
> localoptions() NameError: name 'localoptions' is not defined
I understand that the global function doesn't identify a nested function. Is there any way to specify this nested function to the global function?
def standstill():
print("What now?")
print("Press A to check inventory")
localoptions()
choice = input()
if choice == "A":
print("You have some stuff.")
else:
localanswers()
def chapter1():
def localoptions():
print("Press B to pick a flower.")
def localanswers():
if choice == "B":
print("What a nice flower!")
standstill()
chapter1()
I used classes as Mateen Ulhaq suggested and solved it. Thank you! This is an example of a scalable system for the game.
(I am new to Python and this might not be the best way, but this is how I solved it now.)
class chapter1:
option_b = "Pick a flower."
def standstill():
print("What do you do now?")
print("A: Check inventory.")
if chapter1active == True:
print("B: " + chapter1.option_b)
#Chapter 1
chapter1active = True
standstill()
chapter1active = False

Using functions with variables in Python

I had an assessment for my programming class about calculating insurance using functions. This is the code I was trying to get work but unfortunately I failed:
import time
def main():
print('Welcome to "Insurance Calculator" ')
type_I, type_II, type_III = inputs()
calculationAndDisplay()
validation()
time.sleep(3)
def inputs():
try:
type_I = int(input("How many Type I policies were sold? "))
type_II = int(input("How many Type II policies were sold? "))
type_III = int(input("How many Type III policies were sold? "))
return type_I, type_II, type_III
except ValueError:
print("Inputs must be an integer, please start again")
inputs()
def calculationAndDisplay():
type_I *= (500/1.1)
type_II *= (650/1.1)
type_III *= (800/1.1)
print("The amount of annual earned for type_I is: $", type_I)
print("The amount of annual earned for type_I is: $", type_II)
print("The amount of annual earned for type_I is: $", type_III)
def validation():
cont = input("Do you wish to repeat for another year? [Y/N]: ")
if cont == 'Y' or cont == 'y':
main()
elif cont == 'N' or cont == 'n':
print('Thank You! ------ See You Again!')
else:
print("I'm sorry, I couldn't understand your command.")
validation()
main()
I eventually got it to work by cramming all of the input, calculation, and display into one function. I just want to know how I could have made it work the way intended..
Edit: The program is meant to get the user to input the number of policy's sold and display a before tax total. When I enter a few number inputs it gives me the following error
Welcome to "Insurance Calculator"
How many Type I policies were sold? 3
How many Type II policies were sold? 3
How many Type III policies were sold? 3
Traceback (most recent call last):
File "C:\Users\crazy\Desktop\assessment 2.py", line 38, in <module>
main()
File "C:\Users\crazy\Desktop\assessment 2.py", line 5, in main
type_I, type_II, type_III = inputs()
TypeError: 'NoneType' object is not iterable
Edit: I moved the return line to the suggested line and now it is giving me an unbound variable error:
Welcome to "Insurance Calculator"
How many Type I policies were sold? 5
How many Type II policies were sold? 5
How many Type III policies were sold? 5
Traceback (most recent call last):
File "C:\Users\crazy\Desktop\assessment 2.py", line 39, in <module>
main()
File "C:\Users\crazy\Desktop\assessment 2.py", line 6, in main
calculationAndDisplay()
File "C:\Users\crazy\Desktop\assessment 2.py", line 22, in
calculationAndDisplay
type_I *= (500/1.1)
UnboundLocalError: local variable 'type_I' referenced before
assignment
The problem is, that you save the values in variables which only exist inside the main method but not in the global scope:
type_I, type_II, type_III = inputs()
calculationAndDisplay()
Doing this, the calculationAndDisplay() method do not know the values. You can solve this, by adding parameters to this functions, like this:
def calculationAndDisplay(type_I, type_II, type_III):
#your code
Edit: You code is working without any problem when you perform all calculations in the same method, as now all variables are created inside the same scope. If you use methods, you either have to use function arguments/parameters (the better solution) or use global variables (bad solution, as it undermines the concept of the functions).
In the case, that you later on want to use the modified values of type_I etc. after calling calculationAndDisplay() again, you have to return the modified values in this function, so that you and up with this code:
def calculationAndDisplay(type_I, type_II, type_III):
#your code
return type_I, type_II, type_III
That error which you have mentioned is due to the indentation of the return statement in inputs(). That return statement should be inside inputs function(Because in your case inputs() is not returning type_I,type_II,type_II). Also arguments should be passed to calculationAndDisplay(type_I,type_II,type_III).

Having a compiling error with Python using PyCharm 4.0.5

The reason for me asking the question here is that I did not find a solution elsewhere. I'm having the following error with my PyCharm 4.0.5 program while trying to run a Python script. It was working fine the one day and when I tried using it this afternoon I got the following error after tying to run a program which I am 100% has no errors in it.
In the message box I got the following error:
Failed to import the site module
Traceback (most recent call last):
File "C:\Python34\lib\site.py", line 562, in <module>
main()
File "C:\Python34\lib\site.py", line 544, in main
known_paths = removeduppaths()
File "C:\Python34\lib\site.py", line 125, in removeduppaths
dir, dircase = makepath(dir)
File "C:\Python34\lib\site.py", line 90, in makepath
dir = os.path.join(*paths)
AttributeError: 'module' object has no attribute 'path'
Process finished with exit code 1
I have never seen an error of this kind and don't know where to start tackling this problem.
Any feedback will be greatly appreciated!
The code looks like the following, and I seem to have forgotten to mention that it gives me the exact same error for every single .py script on my computer.
import turtle
wn = turtle.Screen()
alex = turtle.Turtle()
def hexagon(var):
for i in range(6):
alex.right(60)
alex.forward(var)
def square(var):
for i in range(4):
alex.forward(var)
alex.left(90)
def triangle(var):
for i in range(3):
alex.forward(var)
alex.left(120)
def reset():
alex.clear()
alex.reset()
x = True
while x:
alex.hideturtle()
choice = input("""
Enter the shape of choice:
a. Triangle
b. Square
c. Hexagon
""")
if choice.lower() == "a":
length = input("Enter the desired length of the sides: ")
triangle(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "b":
length = input("Enter the desired length of the sides: ")
square(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "c":
length = input("Enter the desired length of the sides: ")
hexagon(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
print("Thank you for using your local turtle services!")
You must have a python file named os.py which is being imported instead of the "real" os module.

NameError: global name 'stealth' is not defined

I'm very new to programming (so sorry if I don't present this problem right).
This is from LPTHW Exercise 36:
My Error:
Traceback (most recent call last):
File "ex36.py", line 329, in <module>
start()
File "ex36.py", line 149, in start
arena()
File "ex36.py", line 161, in arena
if stealth == True:
NameError: global name 'stealth' is not defined
My Assumption:
I thought 'stealth' was defined in the previous function, start(), but the definition didn't carry over to arena(). How do I fix it, and why doesn't 'stealth' from 1 function carry over to another function?
My Code (text-based game in progress):
from sys import argv
script, enemy = argv
...
def start():
print """ Choose a skill to train in
"""
stealth = False
gun = False
knife = False
heal = False
skill = raw_input("> ")
if 'gun' in skill:
print """
"""
gun = True
skill = gun
...
else:
dead()
arena()
def arena():
print """ You enter the arena. Will you:
hide, hunt for food, or search for water?
"""
path = raw_input("> ")
if "hide" in path:
print """ Hide
"""
if stealth == True:
print """ Witness
"""
witness()
else:
battle()
...
else:
print """ Dead
"""
dead()
start()
All advice is greatly appreciated. Thank you for your help.
Variables defined locally in one function have local scope and are not automatically accessible within another, disjunct function. You might want to consider passing stealth to arena when called from start, e.g. arena(stealth), and then stealth would be defined as a parameter of arena, i.e.
def arena(stealth):

Categories

Resources