Passing a string variable between two functions in Python - python

I am having trouble passing a variable from one function to another:
def name():
first_name=input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
return surname()
def surname():
last_name=input("\nCan you tell my your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
return surname()
else:
print("Nice to meet you %s %s." % (first_name,last_name))
I want the last command to print the inputed first_name from def name() and last name from def surname()
I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:
print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
What am I doing wrong?

You need to pass the information in the function call:
def name():
first_name = input("What is your name? ")
if len(first_name) == 0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
surname(first_name) # pass first_name on to the surname function
def surname(first_name): #first_name arrives here ready to be used in this function
last_name = input("\nCan you tell my your last name please?")
if len(last_name) == 0:
print("\nYou did not enter a last name!")
surname(first_name)
else:
print("Nice to meet you %s %s." % (first_name,last_name))
name()

def functionname(untypedparametername):
# do smth with untypedparametername which holds "Jim" for this example
name = "Jim"
functionname(name) # this will provide "Jim" to the function
You can see how they are used if you look at the examples in the documentation, f.e. here: https://docs.python.org/3/library/functions.html
Maybe you should read up on some of the tutorials for basics, you can find lots of them on the python main page: https://wiki.python.org/moin/BeginnersGuide

You can also use while loop to ask the names constantly until there is a valid input.
def name_find():
while True:
first_name=raw_input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name_find()
else:
print("\nHello %s." % first_name)
return surname(first_name)
def surname(first_name):
while True:
last_name=raw_input("\nCan you tell me your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
else:
print "Nice to meet you %s %s." % (first_name, last_name)
break

Related

Trouble with saving and loading dictionary with class instances using pickle

New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()

Ignored properly imported module

So I'm in a beginner Python course trying to learn my first language. I've managed to make it this far, but I'm struggling with this. I want to use a module to perform a function. However, it seems to be completely ignoring my module.
Any suggestions?
import asgn4_module as mod
"""
imports the module, and then prints intro
"""
print ("Assignment 4")
print ()
"""
prompts for names and age.
If they're blank, reprompts them.
"""
firstname = (input ("Please enter your first name."))
while mod.is_field_blank (firstname):
print ("First Name must be entered.")
firstname = (input ("Please enter your first name."))
continue
lastname = (input ("Please enter your last name."))
while mod.is_field_blank (lastname):
print ("Last name must be entered.")
lastname = (input ("Please enter your last name."))
continue
age =(input ("Please enter your age."))
while mod.is_field_blank (age):
print ("Age must be entered.")
age =(input ("Please enter your age."))
continue
while mod.is_field_a_number (age):
print ("Age entered must be a number.")
age =(input ("Please enter your age."))
continue
"""
inputs all received properly, print message calling those variables, then prints the end
"""
if int(age) >= 40:
print ("Well, " + firstname + " " + lastname + "it looks like you're over the hill.")
else:
print ("It looks like you have many programming years ahead of you, " + firstname + " " + lastname)
print ()
print ("End of assignment 4")
This is asgn4_module.py
"""
this module determines if the string is blank, or a number.
"""
def is_field_blank (string):
string == ""
def is_field_a_number (string):
string is int
You are not checking empty but input string against 'g' which I think is not the correct as you have explain your code. And you also have to return the case condition.
Update your module like this
"""
this module determines if the string is blank, or a number.
"""
def is_field_blank (string):
return False if len(string) else True
# for python3
def is_field_a_number (string):
return not string.isnumeric
for python2
# for python2
def is_field_a_number (string):
return not isinstance(string, int)

Why is my if true/elif/else-code not working?

In python, I am trying to make this code accept the user to move forward if he writes "True", and not if he writes "False" for the statement in User_Answer. When I run the code however, I get the "the answer is correct!"-part no matter what I write. The part I am having trouble with starts with "Test_Answer".
Could anyone help me with this?
name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]
print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")
def enter_the_club():
enter_now = input(" \nPress \"enter\" to enter the club... ")
if (enter_now in enter_club) == True:
print (" ")
print ("But as you enter, you are met with an intelegence test. \n It reads:")
check_name = input("What is your name? ")
def list_check():
if (check_name in name_list) == True:
print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
enter_the_club()
elif check_name.isalpha() == False:
print("Haha, nice try %s! Let's hear your real name." % check_name)
list_check()
elif (check_name in name_list) == None:
print ("You will need to give us your name if you want to come in.")
list_check()
else:
print ("I am sorry, but I can not find your name on the list, %s." % check_name)
print ("Are you sure that's your listed name?")
list_check()
list_check()
print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")
Test_Answer = True
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
IQtest()
True is a boolean constant. What the user enters will be either "True" or "False", both character strings. Also, your elif condition cannot be true. What are you trying to do with three decision branches?
Without changing your code too much ... try this?
Test_Answer = "True"
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
Note that I've also corrected your "else" syntax.
Also, you have no value for check_name; I assume this is a global variable that you've handled elsewhere.

Looping with a while statement while reading a string for an integer

I need help encasing the:
if any(c.isdigit() for c in name):
print("Not a valid name!")
inside of a while statement. This pretty much just reads the input for the "name" variable and sees if there's an integer in it. How could I use that in a while statement? I just want it to be if the user inputs a variable into the input, it will print out the string up above and loop back and ask the user for their name again until they successfully enter in a string with no integer, then I want it to break. Any help?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
print("Oh, so your name is {0}? Cool!".format(name))
print("Now how old are you?")
age = raw_input()
print("So your name is {0} and you're {1} years old?".format(name, age))
print("y/n?")
yn = raw_input()
if yn == "y":
break
if yn == "n":
print("Then here, try again!")
print("Cool!")
Use while True and a break to end the loop when a valid name has been entered:
while True:
name = raw_input("What is your name? ")
if not any(c.isdigit() for c in name):
break
print("Not a valid name!")
This is much easier than first initializing name to something that is invalid then using the any() expression in the while test.
Something like this:
name = input("What is your name? : ")
while any(c.isdigit() for c in name):
print ("{0} is invalid, Try again".format(name))
name = input("What is your name? : ")
demo:
What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty
Are you just saying you want a continue after your print("Not a valid name!")?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
continue
print("Oh, so your name is {0}? Cool!".format(name))
...
The continue will just go back to the top of your loop.

Python Modules, passing values to args

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).

Categories