I have this code that works when it's not in the function form, but doesn't when it is one.
I am able to call grade(), but get an error when award() is added.
Here is what I have so far
def award(firstplace, secondplace):
print("")#return
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
count = 0
playeroftheyear = 0
runnerup = 0
firstplace = (" ")
secondplace = (" ")
for results in range (0,5):
name = input("Player Name: ")
fieldgoal = input("FG%: ")
fieldgoal = int(fieldgoal)
if fieldgoal > playeroftheyear:
runnerup = playeroftheyear
secondplace = firstplace
playeroftheyear = fieldgoal
firstplace = name
elif fieldgoal > runnerup:
runnerup = fieldgoal
secondplace = name
award(firstplace, secondplace)
return
grade()
In your code, firstplace, like secondplace exists only in grade, but not in award. Hence, when you try to access it from award, you get the error.
You need to pass secondplace and firstplace as a parameter:
def award(firstplace, secondplace):
print("")
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
...
award(firstplace, secondplace)
return
grade()
Functions set up a new namespace. names that you define inside a function can't be used outside the function unless you explicitly say they can be with the global keyword.
In this case, you're defining names inside of grade (firstplace, secondplace, etc.), but those names are not available to award because they only live inside the grade function. To let them out, you could add:
global firstplace
global secondplace
at the top of your grade function. However, that's definitely not the best approach. The best approach would be to pass them as arguments:
def award(firstplace, secondplace):
...
And then you call award like so:
award(firstplace, secondplace)
Related
I am trying to code something really simple but can't figure out how to use the variable I declared in the first function, in the second function.
Any ideas you might have?
import random
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
def print_user_info():
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
I would create a class:
import random
class request_info(object):
def __init__(self):
self.name = input("What is your name?: ")
self.email = input("What is your email?: ")
def print_user_info(self):
print("Your name " + self.name)
print("Your email " + self.email)
num = random.randrange(100_000, 10**8)
return num
r = request_info()
r.print_user_info()
# What is your name?: Test
# What is your email?: Test#gmail.com
# Your name Test
# Your email Test#gmail.com
# 90584743
I would just pass the variables into the other function like the following code shows:
import random
def print_user_info(name,email):
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
print_user_info(name,email)
You will of course also have to invoke the request_info function once so that the other function gets called.
There are a few ways to do this, but you should think of scope before anything else.
The dirtiest way is to declare a global variable that will be set outside of the function, then assigned within the function.
global someVariable
someVariable = None
someVariable2
someVariable2 = None
def someFunction():
global someVariable
someVariable = 12
global someVariable2
someVariable2 = 24
someFunction()
print(someVariable)
This will get you by, but it's not the best way to work with variables. If all you're writing is 11 or so lines of code, it'll do the trick.
Returns is another way to handle this.
def someFunction():
someVariable = 4
someVariable2 = 13
return (someVariable,someVariable2)
print(someFunction())
By having the function return a tuple will allow you to get both variables accessible to the next function.
Finally, there's classes. I would recommend Classes for more complex code as it keeps things in a nice and neat little container.
class myClass:
someVariable = None
someVariable2 = None
def __init__(self):
self.someVariable = 50
self.someVariable2 = -12
def retValues(self):
someVariable = self.someVariable
someVariable2 = self.someVariable2
return (someVariable,someVariable2)
print(myClass().retValues())
More on Classes here: https://docs.python.org/3/tutorial/classes.html
What you're looking for are return statements, which you can use to assign the output of a function to a variable.
Here, we'll return a tuple and use multiple assignment to call the values in the tuple name and email:
import random
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
return (name, email) # this function now 'returns' this tuple
def print_user_info(name, email):
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
So if you ran the following:
name, email = request_info()
print_user_info(name, email)
(For clarity, this is what's happening in the first line above, but you can combine it into 1 line instead of 3)
user_info = request.info()
name = user_info[0]
email = user_info[1]
Your program would run like so:
What is your name?: Joe Smith
What is your email?: jsmith#gmail.com
Your name Joe Smith
Your email jsmith#gmail.com
Here is one way of doing it. Using a class can help share variables and functions.
import random
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.num = random.randrange(100_000, 10**8)
def print_info(self):
print(f"Your name is: {self.name} \nYour email is: {self.email}")
new_user = User(input("What is your name?"), input("What is your email?"))
new_user.print_info()
I have a global variable that needs to be altered by user input generated by a function.
I'm trying to make a Zork style text game and want the character name, input by the user during a character creation function, to alter a global variable.
I've been able to create a class to store character information and been able to display most of the information in the class on a mock command prompt I have appear when input options are available to the user.
I use a global variable to define the character's name until the character creation stage. I use the 'global' keyword in the creation() function to alter the 'name' variable with user input.
When the prompt is ready to be used it still only displays the name as 00 instead of the input generated during the creation() function
I am exceedingly novice. Any advice, tips or direction would be cherished.
import time
name = "00" ##this is what we want to change
##
def Intro():
print("\n\n\nWelcome to the game.")
time.sleep(1)
print("This is an attempt to make an interactive text based game.")
##
def Creation():
Character_name = input("\nWhat will your Character's name be: ")
time.sleep(1)
print("\nWelcome to the game " + Character_name + " \n" )
time.sleep(1.5)
Character_class = input("In one word, name " + Character_name + "'s profession: ")
t00n = Character_name + " the " + Character_class
global name ##here I am using the global keyword
name = t00n
time.sleep(1)
print("\n" + t00n + "\n")
time.sleep(2)
next_func = input("When ready type 'next' to begin.\n>>>:")
if next_func == "next":
segway()
else:
Jump()
##
def Jump():
Jump_Prompt = input("Just 'Jump' on in\n>>>: ")
if Jump_Prompt == "Jump":
segway1()
else:
Jump()
##
def segway():
print("A room with options to choose from")
prompt()
class Character:
def __init__(self, name, HP, full_HP, AtS, AR):
self.name = name ##should = t00n now?
self.hp = HP
self.full_HP = full_HP
self.AtS = AtS
self.AR = AR
def stat_bar(self):
return '{} {} {} {} {} {}'.format("[Name:]", self.name, "[HP:]", self.hp, "[Max HP:]", self.full_HP)
Player1 = Character(name, 100, 100, 1, 0)
##
def prompt():
_pr = input("<<< " + Character.stat_bar(Player1) + " >>> \n")
return _pr
#Begin
Intro()
Creation()
segway()
##The prompt() function still displays the name as 00 even tho the creation() function is using the 'global' keyword to change the 'name' variable to the user input.
You need to use the global keyword in your prompt, and update Player1.name with that global name
def prompt():
#Take name from global scope
global name
#Assign it to Player1 name
Player1.name = name
_pr = input("<<< " + Character.stat_bar(Player1) + " >>> \n")
return _pr
Then your prompt will work as intended, for example
Welcome to the game.
This is an attempt to make an interactive text based game.
What will your Character's name be: Joe
Welcome to the game Joe
In one word, name Joe's profession: Don
Joe the Don
When ready type 'next' to begin.
>>>:next
A room with options to choose from
<<< [Name:] Joe the Don [HP:] 100 [Max HP:] 100 >>>
Ahhh, took a little bit, but I think I found the problem.
You initialize Player 1 using the name variable before calling Creation(), where you change the global name variable, so Player1 is created with the original name “00.”
Move the line:
Player1 = Character(name, 100, 100, 1, 0)
Put it after Creation() at the bottom but before segway()
Python more or less executes any unindented code (code that isn’t in a function, class, etc.) from top to bottom.
So, moving from top to bottom in your program, it sets name to “00”, then creates Player1 with the original name, then calls Intro(), Creation() (which changes the name to t00n), and finally segway().
names=["aaa","bbb","ccc","ddd","eee"]
itMarks=[90,98,87,98,78]
def printMainMenu():
print(" Main Menu")
print(" =========")
print(" (1)Add Student")
print(" (2)Search Student")
print(" (3)Delete Student")
print(" (4)List Student")
print(" (5)Exit")
choice = int(input("Enter Your choice[1-5]:"))
return choice
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(names)
print("Index is" + i)
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(names)
print("Successfully Deleted" + names)
def removeStudent(names):
name = input("Enter name to remove")
name.remove(name)
print("Successfully deleted" + names)
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(names)
itMarks = input("Enter IT Marks")
itMarks.append(itMarks)
def listStudent(names, itMarks):
for i in range(0, len(names)):
print(names[1], "", itMarks[i])
names = []
itMarks = []
choice = 1
while choice >= 1 and choice <= 4:
choice = printMainMenu()
if choice == 1:
addStudent(names, itMarks)
elif choice == 2:
searchStudent(names, itMarks)
elif choice == 3:
deleteStudent(names, itMarks)
elif choice == 4:
listStudent(names, itMarks)
elif choice == 5:
print("Exit from the program")
else:
print("invalid choice!")
choice = 1
I am new to the programming in Python. The following Python code is written to do some tasks with the array. There are two array named names and itMarks. And there are some functions :
addStudent() - To add students to the array
searchStudent() - To search a student with in the list.
deleteStudent() - To delete the given student from the list.
listStudent() - To list out the all the names of the students in the list.
When the program runs, it asks to select a choice. Then it do the task according to their choice. But when I run this coding it shows the errors.
Please help me. Thanks in advance.
ERROR :
When I select the choice 1 (Add student) and input name after the error is yield.
Traceback (most recent call last):
File "C:\Users\BAALANPC\Desktop\new 3.py", line 59, in <module>
addStudent(names, itMarks)
File "C:\Users\BAALANPC\Desktop\new 3.py", line 42, in addStudent
name = input("Enter Name")
File "<string>", line 1, in <module>
NameError: name 'rtrt' is not defined
Their so many mistakes in naming
In addStudent
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(name) # names cant appent it should be name
itMark = input("Enter IT Marks") # here itmark not itMarks
itMarks.append(itMark)
In searchStudent
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name) # try to find index of name not names
print("Index is" + i)
In deleteStudent
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name) # try to remove name not names
print("Successfully Deleted" + name)
after change above I run its running you have to also change the naming of the variable for all methods
Output
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:1
add student
Enter Name"aaa"
Enter IT Marks111
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:
I'm assuming this is the correct form:
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name)
print("Index is" + i)
note that I changed names to name.
also the same mistake again
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name)
print("Successfully Deleted" + names)
tl;dr revise your code
searchStudent(): You shouldn't need the itMarks argument if you're not using it inside your function at all. names refers to the list of names, but you are really trying to search name. i is an integer that is attempting to be concatenated with a string. Not allowed. It should be str(i).
deleteStudent(): Better to keep your arguments consistent and use names rather than student. Again, same problem as above, should be .remove(name) and you shouldn't need the itMarks argument. print statement should refer to name not names.
removeStudent(): This is the same code as deleteStudent(), but not used, so not sure why it's there.
addStudent(): Typo in the argument, .append(name). You have a global variable and a local variable named the same thing, which are conflicting to the program. Change the input set to itMark and .append(itMark).
listStudent(): print statement has a typo, 1 should be i. Not sure why the empty string is included as well.
Underneath your function def's, you restate your variables as empty lists. This can lead to ValueErrors from a lot of your functions as you're trying to look something up or modify something in an empty list. Simply delete this code.
Additionally, any error will break your while loop. I suggest adding more booleans or using a try except clause to catch these errors.
Good luck!
Whenever I try to display the Firstname with first initial attached to the end, I get an out of string index range error!
def ForeName():
return raw_input("Please enter your Forename: ")
def MiddleName():
return raw_input("please enter your middle name, if none leave blank: ")
def LastName():
return raw_input("Please enter your last name: ")
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT[0:] + LastNameT[0]
elif ForeNameT:
first_username = ForeNameT[0:][0] #i want to display the first name with the initial of the first name attached to the end of the first name.
else:
first_username = ForeNameT[0:] + MiddleNameT[0]
return first_username
print Test()
You can add an argument to Test function by doing def Test(name_method): and then set if to if name_method == 'without_middlename':.
Try to figure out yourself what you would change print Test() to.
I think i know what you are trying to do, try changing your Test function:
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT + LastNameT
else:
first_username = ForeNameT + MiddleNameT + LastNameT
return first_username
notice the changes to the variable names vs. the function names and the return value so print has something to actually print
I'm trying to return the values of a dict when creating an instance of a class in Python, but I keep getting "None" returned instead.
I'm very new to Python, so I'm sure there is an easy answer to this one.
After running the below:
class TestTwo(object):
def __init__(self):
self.attributes = {
'age': "",
'name' : "",
'location': ""
}
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
self.results()
def results(self):
print "You live in %s" % self.attributes['location']
print "Your number is %s" % self.attributes['age']
print "Your name is %s" % self.attributes['name']
d = self.attributes
return d
output = TestTwo().your_age()
print output
I end up with this:
MacBook-Pro-2:python johnrougeux$ python class_test.py
What is your age? > 30
What is your name? > John
Where do you live? > KY
You live in KY
Your number is 30
Your name is John
None
Instead of "None", I was expecting "{'age': '30', 'name': 'John', 'location': 'KY'}"
What am I missing?
Only results() returns something. You need to pass its return value along the call chain by returning it in the other functions if you want them to return something, too:
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
return self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
return self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
return self.results()
Of course this kind of chaining is extremely ugly; but I'm sure you already know that. If not, rewrite your code like this:
in each of those functions, just set the value and do not call one of your other functions. Then add a function such as this:
def prompt_data(self):
self.your_age()
self.your_name()
self.your_location()
In the code using the class, do this:
t2 = TestTwo()
t2.prompt_data()
output = t2.results()
the function your_age() doesn't return any values, of course output is None