I am an absolute beginner in python programming (week 4), and I'm trying to figure this out. I've been going at this for days now but I am truly stuck. I've debugged it to zero errors, but when I run, nothing happens...at all. What am I doing wrong here?
roster =[]
def init_(self, name):
self.name = name
def setName (self,name):
self.name = name
def getName(self):
return self.name
def displayData(self):
print("")
print(" Player's Information")
print("***********************")
print("Player's Name: ", self.name)
def displayMenu():
print("***Selection Menu***")
print("1. View current roster")
print("2. Add a player to the roster")
print("2. Remove a player from the roster")
print("3. Change a player name displayed on the roster")
print("4. Quit")
print()
return int(input("Your Choice?"))
def viewRoster():
print(' '.join(roster))
def addPlayer():
newName = input("Who will bring honor to the squad?:")
roster.append(newName)
def removePlayer ():
removeName = input("Who's off the team?")
if removeName in roster:
del roster[removeName]
else:
print("Sorry", removeName, "is not on this team")
def editPlayer():
oldName = input("What name would you like to change? ")
if oldName in roster:
newName = input("What is the new name? ")
print("Alright,", oldName, "is now called", newName)
else:
print("Sorry,", oldName, "was not found. Are you sure you spelled that right?")
The biggest problem in your code is that though you have defined a lot of functions, you have not called a single one.
Also, the first function should be
def __init__(self, name):
Next up, you need to define a class to encapsulate all your functions and the roster variable. Since it is a class, you add self. in front of your variables like roster.
Then you can import this class elsewhere and call the functions.
Related
So I am new to python, I'm taking classes online, self learning, but I need to know how to pull information out of one function and use it elsewhere in my code.
for example:
def yes_responce():
print("Good! I'm glad i got that right!!!")
def no_responce():
print("Oh no! I'm sorry about that! Let me try that again")
greeting()
def greeting():
name = input("Hello, What is your name?")
age = input("How old are you?")
print("okay,")
print("I understood that you name is", name, "and that you are", age, "years old.")
menu1 = input("Am I correct? enter y for yes, or n for no.")
if menu1 == "y":
yes_responce()
if menu1 == "n":
no_responce()
return {menu1}
greeting()
print(menu1)
the function works great, but how would I be able to call the name or age or menu1 data outside of this function? I'm sorry for asking such a noob question, but I just cant figure it out!
in my head, print(menu1)should print y.
When you define a variable inside of a function, it's called a local variable and is only accessible within that function unless you include it in the return statement. So, if you want a variable to be accessible globally, then you could write:
def greeting():
name = input("Hello, What is your name?")
age = input("How old are you?")
print("okay,")
print("I understood that you name is", name,
"and that you are", age, "years old.")
menu1 = input("Am I correct? enter y for yes, or n for no.")
if menu1 == "y":
yes_responce()
if menu1 == "n":
no_responce()
return name, age, menu1
name, age, menu = greeting()
from database import usernames
class names():
def __init__(self, name):
self.name = name
def name_in_use(self):
if self.name in usernames:
print(f"Sorry {self.name} is already taken. Please come up with a different username.")
name = names(input("How should we call you? ").capitalize())
name.name_in_use()
else:
print(f"Welcome, {self.name}!")
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
name = names(input("How should we call you? ").capitalize())
name.name_in_use()
else:
old_user = input("What is your username? ").capitalize()
print(f"Welcome, {old_user}!")
return
new_user()
How do I extract local name variable from class if it goes into else under name_in_use()?
I tried so many different ways but once outside of function python doesn't see it.
If an instance of names is supposed to use a unique name, that is something that should be enforced either in __init__, or better yet, before you call __init__. Use a class method to verify the name first.
class Name:
used_names = {}
def __init__(self, name):
self.name = name
self.used_names.add(name)
#classmethod
def from_unique_name(cls):
while True:
name = input("How should we call you?")
if name not in used_names:
break
print(f"Sorry {name} is already taken. Please come up with a different username.")
return cls(name)
# Returns an instance of Name or None
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
return Name.from_unique_name()
else:
old_user = input("What is your username? ").capitalize()
if old_user in Name.used_names:
print(f"Welcome, {old_user}!")
return Name(old_user)
else:
print("No user by the name of {old_user}")
user = new_user()
A couple of points to keep in mind:
If multiple threads could be creating new users, you should use a lock to make sure only one thread can append to Name.used_names at a time, and that no other thread can read from it while another thread is updating it.
new_user could also be a class method.
I find few problems in your code.
name_in_use function is recursive with no breaking condition
Code is repeating in new_user functions as well as name_in_use function inside the class
Return statements are missing
Here is the code I propose (Not tested but should work fine)
from database import usernames
class names():
def __init__(self, name):
self.name = name
def name_in_use(self):
if self.name in usernames:
print(f"Sorry {self.name} is already taken. Please come up with a different username.")
return None
else:
return self.name
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
while True:
name = names(input("How should we call you? ").capitalize())
new_name = name.name_in_use()
if new_name:
print(f"Welcome, {new_name}!")
break
else:
user_answer1 = input("You want to try again? [y/n] ")
if user_answer1 == "n":
break
else:
old_user = input("What is your username? ").capitalize()
print(f"Welcome, {old_user}!")
return
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
chooseName()
nameConfirmation()
I apologize for not posting the rest of the code sooner.
This is the output.
Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven
Remove the chooseName( ) call below chooseGender( ) as it has already been called in nameConfirmation( ) definition. It worked for me.
Some modification in your code , Here is updated code:
First edit :
You are calling chooseName() two times ,
Second edit :
You are returning before main logic of your program.
Here
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no
So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = input("Right... So your name is " + str(name) + "? (yes or no) ")
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
return answer
displayIntro()
chooseGender()
nameConfirmation()
As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
So updated code will be as follows:
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
You call the function choseName() and then right after you call nameConfiguration() wich starts by calling choseName(), that's why it is called twice. You can simply remove the choseName() before nameConfiguration().
I've tried searching and trying suggestions people made for others but its not working for me, here is my code:
def CreateAccount():
FirstName = input('What is your first name?: ')
SecondName = input('What is your second name?: ')
Age = input('How old are you?: ')
AreaLive = input("What area do you live in?: ")
return FirstName, SecondName, Age, AreaLive
def DisplayAccountInfo(FirstName,SecondName,Age,AreaLive):
print("Your Firstname is",FirstName)
print("Your Secondname is",SecondName)
print("You are",Age," years old")
print("You live in the",AreaLive," area")
return
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo()
while True:
ConfirmAccountF()
So its just supposed to run indefinitely for now, but what I want it to do is pass the variables from 'CreateAccount' into 'DisplayAccountInfo'.
When I press anything other than n for 'ConfirmAccount' I get that the variables are undefined.
If I set it manually in 'DisplayAccountInfo()' then it doesn't throw any errors.
This is just me messing about and trying to understand python, if anyone can help that would be great.
Use the unpacking operator, *:
DisplayAccountInfo(*CreateAccount())
What this does is takes the tuple of four strings returned by CreateAccount and converts them into four arguments to be passed as separate parameters to DisplayAccountInfo. Whereas if you omitted the * operator and just called DisplayAccountInfo(CreateAccount()), that would pass a single tuple argument to DisplayAccountInfo, resulting in a TypeError exception (because DisplayAccountInfo expects four arguments, not one).
Of course if you also need to save the strings returned from CreateAccount for later use, you'll need to do that in between calling CreateAccount and DisplayAccountInfo.
The variable you declared on CreateAccount() can't be accesed by its name from the outside. To pass the information to another function you need to store its values first:
first_name, second_name, age, area = "", "", "", ""
def ConfirmAccountF():
ConfirmAccount = input("Do you have an account? y,n; ")
if ConfirmAccount == "n":
first_name, second_name, age, area = CreateAccount()
else: #ConfirmAccount -- 'y'
DisplayAccountInfo(first_name, second_name, age, area)
Im learning python and am currently trying to pass values from input to the args for a module I wrote but I have no idea how to start.
Can someone give me some advice?
This is the module im calling
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
This is the code im using to call and pass the values to the args in the above module
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
Im guessing I need to take the input from the user and place it in the variables of the class. I tried that but im guessing im doing everything wrong??
Employee.Age = int(raw_input("How old are you? "))
There's no use to setting a variable in the module instead of using a local variable, and setting whatever you need to set outside the Collection1() function. Note that you are not setting the employee (object) atributes', but the module's - this is probably not what you want. Also, functions, by convention, should be named with initial lowercase.
Your inheritance model is a bit strange. Why are the employee attributes in a different (sub) class? Generally, the attributes go into the main class constructor. If you really want to use a separate class for the attributes, you shouldn't use a subclass at all in this case.
EDIT
Here's what I think you meant to do:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
if you want the Employee in a different file (module), just put it there and from your main code run from Employee import Employee (the first is the module, the second is the class).