Is there any command for calling a function in other function? - python-3.x

Here is my python code. I want to print the 1st function result in the 2nd function's print command in the bolded position. How can I do that?
def Position(self):
if self.is_sitting == True:
print ("sit down")
else:
print("stand up")
def introduce_person(self):
print("The person name is "+ self.name,"." +
"\nThe person's personality is "+
self.personality,".")
print("The person's position is " ,**self.Position()**)

Try this:
class person:
def __init__(self, *args):
self.name, self.personality, self.is_sitting = args
def Position(self):
if self.is_sitting == True:
return "sit down"
else:
return "stand up"
def introduce_person(self):
print("The person name is "+ self.name,"." + "\nThe person's. personality is "+ self.personality,".")
print("The person's position is " , self.Position())
obj=person('ali', 'ambitious', False)
obj.introduce_person()

Related

function without printing none

for some reason I'm printing two Nones, can someone explain how to avoid that?
class Wizard():
def __init__(self,name, gender,power):
self.name = name
self.gender = gender
self.power = power
def fire(self):
print('My power is the fire')
def wind(self):
print ('My power is the wind')
def power_wizard(self):
if power == 1:
print(Wizard.fire(self))
else:
a=print(Wizard.wind(self))
# Create player
name = input('Enter your wizard name: ')
gender = input ('Enter the gender: ')
power = int(input ('Choose your power 1) Fire and 2) Wind:(only numbers)'))
player1 = Wizard(name,gender,power)
print(player1.name)
print(power_wizard(power))
print (The question is how can I not print None or why am I printing None)
My power is the fire
None
None
And also why are 2 None where are the coming from, because when de function wizard_power there only to results.
why am I printing None
When you execute print(power_wizard(power)), the following happens:
the power_wizard() function is called.
in that power_wizard() function, you call the Wizard.fire() or Wizard.wind() methods...
in both methods, you print('My power is...')...
...but you don't return any result.
in the power_wizard() function, you print the result of the Wizard.fire() or Wizard.wind() methods but, as those methods returns nothing, None is printed a first time.
the power_wizard() function returns no results either...
...thus, the outermost print(power_wizard(power)) prints a second None.
That said, your Wizard class and power_wizard() function are a bit tangled...
You could easily remove the Wizard.fire() and Wizard.wind() methods and the power_wizard() function and have:
class Wizard():
def __init__(self, name, gender, power):
self.name = name
self.gender = gender
self.power = power
player1 = Wizard("Gandalf", "male", "fire")
player2 = Wizard("Hermione", "female", "wind")
player3 = Wizard("Draco", "male", "invisibility")
for p in (player1, player2, player3):
print("My name is %s and I have %s power" % (p.name, p.power))
# My name is Gandalf and I have fire power
# My name is Hermione and I have wind power
# My name is Draco and I have invisibility power
If you want to restrict the list of Wizard powers:
class Wizard():
powers = ("fire", "wind") # this is a _class variable_ defining
# all powers available to Wizards
def __init__(self, name, gender, power):
self.name = name
self.gender = gender
if power in Wizard.powers:
self.power = power
else:
raise ValueError("%s is not a Wizard power." % (power))
player3 = Wizard("Draco", "male", "invisibility")
# ValueError: invisibility is not a Wizard power.
If you want to let wizards describe themselves:
class Wizard():
...
def __init__(self, name, gender, power):
...
def __repr__(self):
return "<% is a %s with %s power>" % (
self.name, self.__class__.__name__, self.power)
for p in (player1, player2):
print(p)
# <Gandalf is a Wizard with fire power>
# <Hermione is a Wizard with wind power>
Then, if you want to make a wizard interactively:
def make_wizard():
while True:
name = input("Enter your wizard name: ")
if name:
break
gender = input("Enter its gender: ")
choices = ", ".join(Wizard.powers)
while True:
power = input("Enter its power (%s): " % (choices))
if power in Wizard.powers:
break
return Wizard(name, gender, power)
player1 = make_wizard()
print(player1)
# Enter your wizard name:
# Enter your wizard name: Gandalf
# Enter its gender: male
# Enter its power (fire, wind): invisibility
# Enter its power (fire, wind): fire
#
# <Gandalf is a Wizard with fire power>
If you want powers to be numbered choices:
def make_wizard():
...
choices = ", ".join("%i: %s" % (i, name)
for i, name
in enumerate(Wizard.powers, start=1))
while True:
try:
choice = int(input("Enter its power (%s): " % (choices)))
# will raise ValueError if choice is not a int
power = Wizard.powers[choice-1]
# will raise IndexError if choice-1 is not
# in Wizard.powers range
except ValueError, IndexError:
continue
else:
break
return Wizard(name, gender, power)
player1 = make_wizard()
print(player1)
# Enter your wizard name:
# Enter your wizard name: Gandalf
# Enter its gender: male
# Enter its power (1: fire, 2: wind): invisibility
# Enter its power (1: fire, 2: wind): 3
# Enter its power (1: fire, 2: wind): 1
#
# <Gandalf is a Wizard with fire power>
(that was fun... ;-)
You can only run the print statement if its return is not None like this. Its a bandaid fix.
if player1.name is not None: print(player1.name)

how can i change my print function in Singly linked?

I'm new to data structures in python. i just started them past few weeks. i strucked with some code in python.
here is the code.
class Node:
def __init__(self,value):
self.data=value;
self.next=None;
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(head):
if head is not None:
print(head.data)
display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head;
self.head=temp;
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp;
else:
self.tail.next=temp;
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"));
if n==0:
return;
for i in range(n):
value = int(input("enter element to be inserted"));
self.insert_at_end(value)
list=SinglyLinkedList()
list.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
list.display_List(list.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
list.insert_in_beginning(value);
elif option ==3:
value= int(input("enter element to be inserted: "))
list.insert_at_end(value);
every thing is working fine except display_List function. I want to print the elements using recurssion way. I messed up some where.
but the code snippet is same and i changed the display_List to following function it is working good. i want to change it to recursive way.
def display_List(self):
if self.head is None:
print("List is empty")
return
else:
print("List is:",end=" ");
p=self.head
while p is not None:
print(p.data,end=" ")
p=p.next;
if option == 1:
list.display_List()
this function is working fine insteed of recursive. can someone please help me to correct this code.
You have to call this function with class object.
You defined it befor , here:
Do not use 'list' use other as 'l' , list is keyword.
l=SinglyLinkedList()
Must called function like:
l.display_List(head.next)
So your function will be like this:
class Node:
def __init__(self,value):
self.data=value
self.next=None
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(self,head):
if head is not None:
print(head.data)
l.display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head
self.head=temp
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp
else:
self.tail.next=temp
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"))
if n==0:
return
for i in range(n):
value = int(input("enter element to be inserted"))
self.insert_at_end(value)
l=SinglyLinkedList()
l.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
l.display_List(l.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
l.insert_in_beginning(value)
elif option ==3:
value= int(input("enter element to be inserted: "))
l.insert_at_end(value)
ยด
I tested this code , it work well, without any problem.

Python TypeError object() takes no parameters while class

class Tank(object):
def _init_(self,name):
self.name = name
self.alive = True
self.ammo = 5
self.armor = 60
def _str_(self):
if self.alive:
return "%s (%i armor and %i shells left)"%(self.name,self.armor,self.ammo)
else:
return "%s is DEAD !" % self.name
def fire_at(self,enemy):
if self.ammo >= 1:
self.ammo-=1
print(self.name," fires on ",enemy.name)
enemy.hit()
else:
print(self.name," has no shells!")
def hit(Self):
self.armor-=20
print(self.name," is hit !")
if self.armor<=0:
self.explode()
def explode(self):
self.alive = False
print(self.name," explodes !!!!")
from tank import Tank
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Crane") }
alive_tanks = len(tanks)
while alive_tanks > 1:
print()
for tank_name in sorted(tanks):
print(tank_name,tanks[tank_name])
first = raw_input("Who fires ?").lower()
second = raw_input("Who at ?").lower()
try:
first_tank = tanks[first]
second_tank = tanks[second]
except KeyError:
print("No such Tank ")
continue
if not first_tank.alive or not second_tank.alive:
print("One of those is dead!")
continue
print()
print("*"*30)
first_tank.fire_at(second_tank)
if not second_tank.alive:
alive_tanks -= 1
print("*"*30)
for tank in tanks.value():
if tank.alive:
print(tank.name," is the winner !")
break
On running it gives error :
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Crane") }
TypeError: object() takes no parameters
What I need to resolve it?
class init methods are ddunder methods, you need to declare the init method with two underscores before and after, if not the the default init method is called.
__init__(self, name)
instead of
_init_(self, name)
Same goes for your str method, it needs to be:
__str__

Calling global variable causes error when using it for pickling in python 3

I'm trying to save and load files by player name, but it errors when I try to call PlayerIG.name for the path. I've declared global PlayerIG higher up.
Basically I use the PlayerIG to load and then overwrite the values as the name remains the same anyway. The player doesn't have to know and I couldn't find an easier way to do this
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.base_attack = 10
self.gold = 10
self.pots = 1
self.weap = ["Rusty Sword"]
self.curweap = self.weap
#property
def attack(self):
attack = self.base_attack
if self.curweap == "Rusty Sword":
attack += 5
if self.curweap == "Great Sword":
attack += 12
return attack
def attack_damage(self, attack):
damage = random.randint(attack / 2, attack)
return damage
def start():
os.system('clear')
print ("Hello, what is your name?")
options = input("--> ")
global PlayerIG
PlayerIG = Player(options)
name = "Your name is: " + PlayerIG.name
send_status(name)
main()
def main():
os.system('clear')
menutext = "Welcome to text RPG!\n 1.) Start\n 2.) Load\n 3.) Exit\n"
print (menutext)
options = input("-> ")
if options == "1":
Menu()
elif options == "2":
if os.path.exists(PlayerIG.name == True:
os.system('clear')
with open(PlayerIG.name, 'rb') as f:
PlayerIG = pickle.load(f)
loaded = "You loaded your save"
print (loaded)
send_status(loaded)
time.sleep(2)
Menu()
else:
noload = "You have no save file for this game."
print (noload)
time.sleep(2)
main()
elif options == "3":
sys.exit()
else:
main()

how to check if the user exist in database list

After so many hours I still can't figure out how to check if the name and password user input exist in my data. For example, when I ask Please input customer name: and they input Sam than I ask again Please input customer password: and the input is janos i want customer_menu() function to be called. thanks
customers_list = []
class BankSystem(object):
def __init__(self):
self.customers_list = []
self.load_bank_data()
def load_bank_data(self):
customer_1 = Customer("Sam", "janos", ["14", "Wilcot Street", "Bath", "B5 5RT"])
account_no = 1234
account_1 = Account(5000.00, account_no)
customer_1.open_account(account_1)
self.customers_list.append(customer_1)
def customer_login(self, name, password):
if name in customers_list and password in customers_list:
self.name = name
self.password = password
self.customer_menu()
else:
print("sorry %s, it doesn't look like you are a customer"%name)
exit()
def main_menu(self):
print ("1) Customer login")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_main_option(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
name = input ("\nPlease input customer name: ")
password = input ("\nPlease input customer password: ")
msg = self.customer_login(name, password)
print(msg)
person.py
class Person(object):
def __init__(self, name, password, address = [None, None, None, None]):
self.name = name
self.password = password
self.address = address
def get_address(self):
return self.address
def update_name(self, name):
self.name = name
def get_name(self):
return self.name
def print_details(self):
print("Name %s:" %self.name)
print("Address: %s" %self.address[0])
print(" %s" %self.address[1])
print(" %s" %self.address[2])
print(" %s" %self.address[3])
print(" ")
def check_password(self, password):
if self.password == password:
return True
return False
def profile_settings_menu(self):
#print the options you have
print (" ")
print ("Your Profile Settings Options Are:")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Update name")
print ("2) Print details")
print ("3) Back")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_profile_options(self):
loop = 1
while loop == 1:
choice = self.profile_settings_menu()
if choice == 1:
name=input("\n Please enter new name\n: ")
self.update_name(name)
elif choice == 2:
self.print_details()
elif choice == 3:
loop = 0
customer.py
from person import Person
class Customer(Person):
def __init__(self, name, password, address = [None, None, None, None]):
super().__init__(name, password, address)
def open_account(self, account):
self.account = account
def get_account(self):
return self.account
def print_details(self):
super().print_details()
bal = self.account.get_balance()
print('Account balance: %.2f' %bal)
print(" ")
for customer in customers_list:
if customer.name == name:
if customer.password == password:
...

Resources