passing one function to another inside a for loop - python-3.x

New to programming. I wrote a program that Asks the user to enter the name, age and shoe size for four people and adds it to a dictionary. In fact, it works even when I don't use one function as an argument for another function. However, when i try to pass get_user_info() to store_user_info it doesnt work. I also tried to pass get_user_info to three separate variables and then passed these variables to store_user_info and it still didn't work. I am probably making a dumb error. Sorry its kind of a basic type of query but I just started learning programming. Any guidance is appreciated.
FOLLOWING CODE DOESN'T WORK: IT RUNS THE FOR LOOP BUT NEVER PROMPTS FOR THE INPUT FOR MORE THAN ONCE
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info(user_info):
user_information = {}
for i in range(3):
name, age, shoesize = user_info
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
=
store_user_info(get_user_info())
YET THE FOLLOWING WORKS and the loop works 3 times as expected:
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info():
user_information = {}
for i in range(3):
name, age, shoesize = get_user_info()
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
store_user_info()

Related

make all the variables global inside a function of python3

How to declare all the variables global inside a function for python-3 for the below code .I have to use many variables with name "dairy" like "dairy_choice",etc and wish to use again in program.
def dairy_menu():
for key in dairy:
print(key,":",dairy[key])
global dairy_choices
dairy_choices = {}
while True:
global dairy_choice
dairy_choice = input("Enter your desired product = ")
if dairy_choice not in dairy_key_list:
print("Enter a valid choice from the above list!")
if dairy_choice in dairy_key_list:
dairy_choice_quantity = int(input("Enter the desired quantity = "))
dairy_choices[dairy_choice]=dairy_choice_quantity
dairy_choice_more = input("Continue shopping Dairy? [y/n] = ")
if dairy_choice_more=="y":
continue
elif dairy_choice_more=="n":
print("Your choices were:")
for key in dairy_choices:
print(key,":",dairy_choices[key])
break

cant get my while loops working the way i want it to

i am trying to get this code to work properly where if you input a number it will revert you back to the name=input prompt and once you enter alphabetical characters and not numerical characters it will allow you to move on to the next set of code but it keeps returning you to the name = input and doesnt let you through the rest of the code
def setup():
global name
global HP
global SP
global MP
while True:
try:
name = input('can you please tell me your name? ')
name2=int(name)
if not name.isalpha==True and not name2.isdigit==False:
break
except Exception:
print('please input your name')
continue
HP = randint(17,20)
SP = randint(17,20)
MP = randint(17,20)
print('welcome ['+name+':]: to the moon landing expedition')
There is a problem at name2=int(name) This causes an exception unless you type all numbers. In turn, this triggers the Exception and loops it forever. Your while loop seems fine.
What i think you should do:
while True:
name = input('What is your name')
isnum = False
for i in name:
if i.isnumeric():
isnum = True
break
if isnum:
print('Please type your name.')
continue
break

How to have a function return a variable that can be used in the rest of the program? Python 3

I'm trying to make a name generator function which will then return the parts of the name for use in the rest of my program. I put this inside of a function so that I could give the user the option to regenerate the name, instead of being stuck with the first one.
Putting the lists inside the function, and then being able to call the function again causes the random numbers to recalculate, so a new name is generated, but when I try to use "return" to move the variables outside of the function, I get an error.
There's probably a better way to do this, but I'm drawing a blank.
Here's what I have:
def naming():
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'esquire', 'the huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
return title, name, descriptor
if choice == "no":
print("Sorry, I'll try again.")
naming()
else:
print("Sorry I don't understand.")
naming()
I actually figured it out on my own. Here's what I did:
while True:
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'scissor-handed', 'huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
break
if choice == "no":
print("Sorry, I'll try again.")
else:
print("Sorry I don't understand.")
The code works fine, have you tried to atribute the return values to variables?
IE:
title, name, descriptor = naming()

It asks to give the values but instead of giving an answer. It is giving me None

Here I created a module.
class Employee:
def __init__(self):
self.name = input("Enter your name: ")
self.account_number = int(input("Enter your account number: "))
def withdraw(self): # it receives values from for
if withdraw1 > current_balance:
print ("You have entered a wrong number: ")
else:
print ("The current balance is: ", current_balance - withdraw1)
import TASK2 # I am importing the module I created
c = TASK2.Employee()
def for(self):
c.withdraw1 = int(input("enter number: "))
c.current_balance = int(input("Enter the current balance: "))
d = method(c.withdraw) # here I am trying to pass the values to withdraw
print (d)
The problem I get is that although it asks for the values instead of giving me an answer it gives me None.
Here's my take on your code.
# TASK2.py
class Employee:
def __init__(self):
self.name = input("Enter your name: ")
self.account_number = int(input("Enter your account number: "))
# make sure you initialise your member variables!
self.withdraw_val = 0 # withdraw1 is ambiguous, so I use withdraw_val instead
self.current_balance = 0
# receives values from for ### no it doesn't, right now, it GIVES values TO your "for" function
def withdraw(self):
if self.withdraw_val > self.current_balance: # remember to use "self." to
# access members within the class
print ("You have entered a wrong number: ")
else:
# again, remember "self."
print ("The current balance is: ", self.current_balance - self.withdraw_val)
# TASK2sub.py
import TASK2
c = TASK2.Employee()
def for_employee(employee): # (1) don't use "self" outside a class
# it's contextually unconventional
# (2) "for" is a keyword in Python, don't use it for naming
# variables/functions, it'll mess things up
employee.withdraw_val = int(input("Enter value to withdraw: "))
employee.current_balance = int(input("Enter the current balance: "))
return employee.withdraw_val # not entirely sure what you want to return
# but you should definitely return something
# if you're going to assign it to some variable
d = for_employee(c.withdraw()) # "for_employee" function needs a return statement
# ".withdraw()" method should also require a return statement
print(d)
Note: I'll be referring to your original for function as for_employee from now on. Also note that I'm still hazy about what you're trying to accomplish and that there is most probably a more suitable name for it.
Since your original for_employee function didn't return anything, it returns None by default. (This explains the output you saw.)
I think you're misunderstanding how functions work in general. For example,
d = for_employee(c.withdraw())
print(d)
Your comment for the .withdraw() method is inaccurate.
"it receives values from for"
More accurately, c.withdraw() will first be computed, then whatever it returns is passed into the for_employee function as a parameter. Instead of "receiving values from", the withdraw method "gives values to" the for_employee function.
Something more reasonable would be
c.withdraw() # on a line by itself, since it doesn't return anything
d = for_employee(c) # pass the entire object, since you'll be using self.withdraw_val and whatnot
print(d)
Another issue is with conventional naming. This is what I get from the IDLE (with Python 3.7) when defining a function named for
>>> def for(a): return a
SyntaxError: invalid syntax
Again, for is a keyword in Python, don't use it for naming your variables, functions, or classes.
With self, it's less severe (but I could see that it's confusing you). self is more of a convention used in class methods. But for_employee isn't a class method. So conventionally speaking, the parameter shouldn't be named self.
(I find the code spaghetti-ish, it might benefit if you refactor the code by moving the for_employee method into the class itself. Then it would completely make sense to use self.)

why doesn't the highlighted section of code work and what do i need to change to make it able to work

I just deleted my previous question as someone made it embarrassingly obvious that I didn't ask an actual question with a main goal.I apologise for this.
I am only referring to the last part of the code. The "A" option as i cannot figure out why it is incorrect
The full thing works other than the A section it says there is a syntax error. That's it.
I've tried re placing the brackets and playing around with them and so on.
def Jobs():
def Parse_Line(Job_Line):
Job_Line = Job_Line.strip()
Estimate_Number, Estimate_Date, Customer_ID, Final_Total, Job_Status,Amount_Pay= Job_Line.split(",")
Painting_Job = {
'Estimate_Number':Estimate_Number,
'Estimate_Date':Estimate_Date,
'Customer_ID':Customer_ID,
'Final_Total':Final_Total,
'Job_Status':Job_Status,
'Amount_Pay':Amount_Pay,
}
return Painting_Job
Job_List = []
with open("paintingJobs.txt", "r") as Painting_Jobs:
for line in Painting_Jobs:
Job_List.append(Parse_Line(line))
return Job_List
def Accepted(job):
return job['Job_Status'] == "A"
def Outstanding(job):
return int(job['Final_Total']) - int(job['Amount_Pay'])
Job_List = Jobs()
print ("\nOption A: Search for an estimate\n\nOption B: Dislay the outstanding payments\n\nOption C: Display your total revenue\n\nOr Press Q to quit")
Option_Choice = input("Which option do you want to do?")
if Option_Choice == "A" or Option_Choice == "a":
Estimate_no = input("Please enter the required estimate number so we search our database: ")
Estimate_Found = Estimate_no
job in Job_List if ['Estimate_Number'] == Estimate_no
if Estimate_Found:
print (Estimate_Found)

Resources