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)
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()
I need to write a function that takes another function as a parameter. The parameter function is a black box and I don't have control over it. It calls the input function an unspecified number of times. I want to call the parameter function inside my function, then somehow get all user inputs (maybe as a multiline string?), and then return it in my function. Is there any way that I can record all the strings typed into stdin after running the parameter function?
def func():
input("What is your name? ")
input("How old are you? ")
input("What's your favourite animal? ")
def capture_input(func_to_run):
func_to_run()
return ... # somehow return all the previous writes to stdin here
Example run in the shell
>>> capture_input(func)
What is your name? Mike
How old are you? 100
What's your favourite animal? Dog
"Mike\n100\nDog" # <- This is what the function should return
If I follow what you want to do correctly. Store the inputs in a variable, then return them as a tuple. Then return your function inside capture_input.
def func():
name = input("What is your name? ")
age = input("How old are you? ")
animal = input("What's your favourite animal? ")
return name, age, animal
def capture_input(func_to_run):
return func_to_run()
When I run the program it asks for my input multiple times even after I've entered it once already.
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
Asks the user to input a name which is the key to a value, which it returns
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
You need to ask the user input first instead of comparing the user input directly to the key.
You do not want to do it like that. Take a look at the following instead:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
You do not have to loop through your dict and check the user input against each value individually (plus you are forcing the user to update\re-enter his input continuously).
Just receive it once and process it.
If you want to keep the loop running to allow for multiple queries, use while like so:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My code is supposed to only accept letters (for example Jack would be accepted, and jack1 would not be accepted).
It prompts the user for their first and last name then stores them. Once I had written the code for the first name, I tested it to see if I had written the code correctly for the first name, but it kept giving me this error .
In the answers can you please show how to make this work with only numbers being allowed?
Code
import random
operators = ["+", "-", "*"]
def greeting(first_name, last_name):
print ("Hello", first_name + " " + last_name)
Play = input('Are you ready to begin?')
if Play == 'yes':
print("Great", first_name + ", lets begin")
else:
greeting(first_name, last_name)
def Players_input():
print ("Welcome to the Arithmetic Quiz")
first_name = input("Please enter your first name: ")
if all(x.isalpha() or x.isspace() for x in first_name):
last_name = input("Please enter your last name: ")
greeting(first_name, last_name)
else:
print("Only alphabetical letters and spaces: no")
Players_input()
score = 0
for i in range(10):
first_number = random.randint(1,12)
second_number = random.randint(1,12)
op = random.choice(operators)
print (first_number, op, second_number, " = ?")
users_answer = int(input())
if op == "+":
right_answer = first_number + second_number
elif op == "-":
right_answer = first_number - second_number
elif op == "*":
right_answer = first_number * second_number
if users_answer == right_answer:
print("Well Done!")
score += 1
else:
print ("Sorry but thats the wrong answer, the right answer is: " + str(right_answer) + ". Better luck next time")
print (first_name, "Your final score in the Arithmetic Quiz is", str(score), "out of 10")
The answer for the first problem:
You never defined first_name outside of Players_input. This value is just stored inside the function, and get's deleted afterwards. (more about this in the link added by gjttt1)
There are two ways to solve this:
You could make first_name global. But this is a bad style, so I wouldn't use this option. You would add global first_name at some point in Players_input, before it is written to (so either before or directly after the first print call)
You could return first_name, this is the preferred way. Add a return first_name at the end of Players_input, and replace Players_input() with first_name = Players_input().
The answer to the second problem:
Just use this function instead of int(input()) (replace this line with int_input()):
def int_input(prompt="", error_message="You didn't enter an integer!"):
while True: # repeat this until the function returns
inp = input(prompt) # get the input after autputting the prompt.
try: # Try to...
return int(inp) # turn it into an integer. If it works, return it.
except ValueError: # If it didn't work, it raised a ValueError. In this case...
if error_message: # print the error_message if it is not "", false or None.
print(error_message)
Then you have a third problem: You should just use lowercase letters in function names, to distinguish them from classes. This is just about your style, but it'll certainly help to develop a good, clear coding style.
I hope I could help,
CodenameLambda
The first_name variable is out of scope when you are trying to use it. It belongs to the Players_input() function.
Read this article on scoping to get more of an idea of what is happening
Look at the error. It's telling you that the first_name variable is not defined. This is because it is a local variable in the Players_input function and cannot be used elsewhere. Variables that are defined inside a function are put on the stack in memory and are destroyed when that stack frame is pushed off the stack. You call this 'going out of scope'.
I recommend that you look up information about the scope of variables.
you can declare first_name=('hi') earlier in the code and then when you call it in as an input function you can write it like:
first_name=str(input('Please enter your first name: '))
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.