Send input from function to class - python-3.x

Python beginner here.
I am having hard time understanding how to get user input from function to use it in one of my class methods
class...
def setFirstStageSpeed(self, s):
s = # FIRST_STAGE_SPEED from main()
self.Speed = s
...
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
...
So as shown above, I am trying to get the input value on FIRST_STAGE_SPEED to the setFirstStageSpeed() method.

Here is a solution.you should creaete a instance of SpaceCraft.that's OOP style.
class SpaceCraft:
def setFirstStageSpeed(self, s):
self.Speed = s
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
# make a instance of SpaceCraft.if you not familiar with OOP(Object-oriented programing).you should study about it
spaceCraft = SpaceCraft()
# then call the instance method.set the first stage speed
spaceCraft.setFirstStageSpeed(FIRST_STAGE_SPEED)

Related

i want to print dictionary keys and values separately with given string in python for my project

I'm not able to finish the project given below if someone help me with the particular function paasenger_login ...help me out
The project is flight reservation system with basic pyhton programming
a. Passenger
1. sign in
2.check availability and fare
3.book ticket
b. Cashier
1.approve
2.issue ticket
the code is below
s=[]
class passenger:
pass
class book:
d={}
f={}
pact=1-000-000
new=0
class cashier:
def caslogin():
while True:
print("\t1.Filling Tickets\n\t2.passenger Info\n\t3.Approve Tickets\n\t4.Logout")
x=input()
if x=='1':
if (book.new==0):
flight=int(input("Enter the no of flights: "))
for i in range(flight):
print("Enter name of the flights: ")
q=input()
print("Enter the price for to travel:\n")
op=[]
op.append(input())
book.d[q]=op
print("Successfully loaded:\n")
book.new=1
else:
print("\n\tAlready loaded")
elif x=='2':
if book.pact<=1-000-000:
print("NO user found!................")
else:
for i in range(len(s)):
print(s[i].name,i+1-000-000,s[i].history,s[i].report)
elif x=='3':
if book.pact<=1-000-000:
print("NO record found!................")
else:
for i in s:
print(i.name,i.report)
else:
break
def passenger_login(rn):
while True:
print("Successfully logged in... \n\t1.Book Tickets\n\t2.Approval\n\t3.Logout")
n=input()
if n=='1':
if len(book.d):
for i in book.d:
print(str(i),str(book.d[i]))
else:
break
def __main__():
print("Air Asia\n")
while True:
print("Login as\n\t1.Cashier\n\t2.passenger\n\t3.Exit")
n=input()
if n=='1':
cashier.caslogin()
elif n=='2':
while True:
print("Passenger Info\n\t1.Sign in\n\t2.Sign up\n\t3.Logout")
x=input()
if x=='1':
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Enter the serial no:")
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Try after few minutes")
if reg != len(s):
print("NO account found")
else:
if s[reg-1-000-000].ps==Pass:
passenger_login(reg-1-000-000)
elif x=='2':
s.append(passenger())
s[book.pact - 1-000-000].name=input("Enter your name:\n")
s[book.pact - 1-000-000].ps=input("create password:\n")
s[book.pact - 1-000-000].history=0
s[book.pact - 1-000-000].report="New user"
print("Your serial no is : ",book.pact)
book.pact+=1
else:
break
else:
break
__main__()

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__

Need help understanding why my code doesn't run [python]

So my goal is to make an ordering system for a cafe with various types of coffee available. Right now I'm having trouble understanding why my code doesn't run, whenever I execute the code nothing happens and I'm not sure why
class Coffee(object):
def __init__(self,name):
self.name = name
def coffee (self, coffee_type, price):
self.coffee_type = coffee_type
self.price = price
class Order(object):
def __init__(self, name):
self.name = name
def newOrder (self, coffee_type, coffee_amount):
this.coffee_type = coffee_type
this.coffee_amount = coffee_amount
class Main(object):
def __init__ (self, name):
self.name = name
from Coffee import coffee
flat_white = coffee("1 : Flat White", 3.50)
long_black = coffee("2 : Long Black", 3.50)
cappuccino = coffee("3 : Cappuccino", 4.00)
espresso = coffee("4 : Espresso", 3.25)
latte = coffee("5 : Latte", 3.50)
Ordering = 'Y'
while Ordering == 'Y':
try:
order_coffee = int(input("What coffee would you like to order?", pprint (vars(coffee))))
break
except:
ValueError
print ("wrong input")
order_amount = input("How many would you like to order?")
if order_coffee == 1:
new_Order(flat_white, order_amount)
elif order_coffee == 2:
new_Order(long_black, order_amount)
elif order_coffee == 3:
new_Order(cappuccino, order_amount)
elif order_coffee == 4:
new_Order(espresso, order_amount)
elif order_coffee == 5:
new_Order(latte, order_amount)
else:
print ("Please enter a valid number")
break
It looks like there are several issues with your code. I will try to help you out with a couple.
First, no need for the __init__ method to accept a name. Just make the method accept the necessary information for the object:
class Coffee(object):
def __init__ (self, coffee_type, price):
self.coffee_type = coffee_type
self.price = price
class Order(object):
def __init__(self, coffee_type, coffee_amount):
self.coffee_type = coffee_type
self.coffee_amount = coffee_amount
Second, since it does not really do anything, you can replace the Main class to an execution in a conditional as is typically seen in Python programs/scripts:
if __name__ =="__main__":
... # put main code here
Next, the except as it is written will catch all exceptions making debugging more difficult. If you only want to catch the ValueError, do:
except ValueError:
print ("wrong input")
If you use the current flow (i.e. with the try except block, you should put all of the order logic within the try block as it does not make any sense outside. Also, the necessary variables needed (order_coffee) will not be defined if you have a ValueError.
Adding a break after accepting the order input will cause you to break out of the ordering loop after an order is entered. This is probably not intended behavior. No break is needed here. Ditto for after outputting "Please enter a valid number".
When creating an Order, you just need to call Order(coffee_type, coffee_amount). When you create this order, make sure to set it to a variable too. probably something like:
new_order = Order(flat_white, order_amount)
Printing "Please enter a valid number" and "wrong input" is slightly redundant. You only need one of them to print under invalid input.
Lastly, pprint will print stuff out then return None so print(..., pprint(x)) will print an extra None once it has finished pretty printing x, instead just call pprint as if it was another call to print.
-- --
Making all of these changes, you will end up with something like:
class Coffee(object):
def __init__ (self, coffee_type, price):
self.coffee_type = coffee_type
self.price = price
class Order(object):
def __init__(self, coffee_type, coffee_amount):
self.coffee_type = coffee_type
self.coffee_amount = coffee_amount
if __name__ =="__main__":
coffee_available=[Coffee("1 : Flat White", 3.50),
Coffee("2 : Long Black", 3.50),
Coffee("3 : Cappuccino", 4.00),
Coffee("4 : Espresso", 3.25),
Coffee("5 : Latte", 3.50)]
ordering = 'Y'
while ordering == 'Y':
print("Coffee Type\t\tPrice")
print("-----------\t\t-----")
for coffee in coffee_available:
print("{}\t- - -\t$ {}".format(coffee.coffee_type,coffee.price))
print()
order_coffee = int(input("What is the number of the coffee you want? "))
order_amount = input("How many would you like to order? ")
new_order = None
if order_coffee >= 1 and order_coffee <=5:
new_order = Order(coffee_available[order_coffee-1], order_amount)
else:
print ("Please enter a valid number")

Can anyone see why i get UnBoundLocal Error for my score varible

Can anyone see why I get "UnBoundLocal Error" for my score varible?
import random
Score=0
def Main_Menu(Score):
print("=============================")
print("WELCOME TO MY QUIZ")
print("=============================")
while True:
Username=input("What is your name?")
if Username.isalpha():
if len(Username)>11:
print("You are only a maximum of 11 characters")
else:
Username=Username.title()
break
else:
print("Letters only")
while True:
while True:
Option=input("What do you want to do?\n1 For Quiz\n2 To Quit.")
if Option.isdigit():
Option=int(Option)
break
else:
print("Numbers Only.")
if Option==1:
for x in range(10):
Quiz(Username)
print("You have scored",Score,"point out of 10!!\n")
elif Option==2:
input("Press Enter to quit the program")
break
else:
print("You only have 2 options")
Quiz(Username)
def Quiz(Username):
Tries=3
Number_One=random.randint (0,10)
Number_Two=random.randint (0,10)
Arithmetic_Operator=random.choice(["+","-","*",])
if Arithmetic_Operator=="+":
print(Username,"\nWhat is",Number_Two,"+",Number_One,"?")
Answer=Number_Two+Number_One
elif Arithmetic_Operator=="-":
print(Username,"\nWhat is",Number_Two,"-",Number_One,"?")
Answer=Number_Two-Number_One
elif Arithmetic_Operator=="*":
print(Username,"\nWhat is",Number_Two,"*",Number_One,"?")
Answer=Number_Two*Number_One
while Tries!=0:
while True:
Guess=input("Answer: ")
if Guess.isdigit():
Guess=int(Guess)
break
else:
print("Numbers Only.")
if Guess==Answer:
print("Well Done.You got it right.\nYou have a point")
Score=Score+1
break
elif Guess!=Answer:
Tries=Tries-1
print("You have",Tries,"tries left")
if Tries==0:
print("The answer is",Answer)
Main_Menu(Score)
You are getting the UnboundLocalError: local variable 'Score' referenced before assignment error because the Quiz method doesn't have a local variable Score but is trying to read from it. You probably meant to use the the global variable Score, but it's not available in the method scope without using the global statement. You can fix this by adding global Score in the beginning of the Quiz method.
However, using globals in python code is another discussion, I would strongly recommend avoiding them, unless there's really a proper reason to use them. Please see this SO for more details and discussion.

Resources