Python function parameter as a global variable - python

I have written the following function, it takes in a variable input_name. The user then inputs some value which is assigned to input_name. I want to know the best way to make input_name accessible outside of the function. I know that defining a variable as global, inside a function, means that is can be used outside of the function. However, in this case the variable as actually a parameter of the function so I am not sure how to define it as a global variable. I appreciate any help with this, please find the code in question below:
def input(input_name, prompt):
while True:
data = raw_input(prompt)
if data:
try:
input_name = int(data)
except ValueError:
print 'Invalid input...'
else:
if input_name >= 0 and input_name < 100:
print 'Congratulations'
break
input_name = 'Please try again: '
else:
print 'Goodbye!'
break
month = 0
day = 0
year = 0
century = 0
input(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ")
input(day, "Please enter the day (from 1-31): ")
input(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ")
input(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ")
A = month
B = day
C = year
D = century

The simplest thing would be to return the value, and assign it outside the function:
def my_input(prompt):
#.. blah blah..
return the_value
month = my_input("Please enter the month")
# etc.

Other people are saying something like this:
def input(prompt):
return value
value = input(param1,param2, ...)
And that's what you really want to be doing, but just so you know, you can use globals() for changing global variables:
def input(input_name, prompt):
globals()[input_name] = value

What you want to do is probably a bad practice. Just return input_name from the input function.
def input(param1,param2):
return value
value = input(param1,param2, ...)

Related

Checking if inputted strings are equal to strings in list?

I'm working on a project that involves building a simplified version of a calendar agent that asks the user for when they want to schedule an appointment and does it for them (if that slot is free). This is the code I have so far:
def find_index(val, seq):
for index in range(len(seq)):
place = seq[index]
if place == val:
return index
else:
return int("-1")
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
else:
return False
def init_nested_list(size_outer, size_inner):
cal = []
for outer_index in range(size_outer):
nested_list = []
for inner_index in range(size_inner):
nested_list.append("-")
cal.append(nested_list)
return cal
def get_input(possible_vals, day_or_time_string):
count = 0
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
nested_list = find_val(answer, possible_vals)
while answer in possible_vals:
break
else:
count = count + 1
answer = input("Invalid entry. Please enter a valid day: ")
if count == 3:
print("This is getting silly - still not a valid entry")
answer = input("Please do try to enter a valid day: ")
count = 0
return answer
def book_slot(cal,days_labels, times_labels, day, time): **ignore this function, haven't finished it yet**
find_index(day, days_labels)
def start_scheduler(cal, days_labels, times_labels):
while True:
day = get_input(days_labels, "day")
time = get_input(times_labels, "time")
book_slot( cal, days_labels, times_labels, day, time)
print("--------------------------------- ")
res = input("Did you want to book more appointments (type n for no, any other key for yes)? ")
if res == "n":
break
days_labels= ["Monday","Tuesday","Wednesday","Thursday", "Friday"]
times_labels = ["9","10","11","12","1","2","3","4","5"]
calendar = init_nested_list(len(days_labels), len(times_labels))
print("Welcome to the acupuncture booking system. ")
start_scheduler(calendar, days_labels, times_labels)
This is what the complete output should look like so far:
Welcome to the acupuncture booking system.
What day would you like your appointment? saturday
Invalid entry. Please enter a valid day: Monday
What time would you like your appointment? 24
Invalid entry. Please enter a valid time: 9
---------------------------------
Did you want to book more appointments (type n for no, any other key for yes)?
However, it seems that no matter what I input when the function asks me for the date/time of the appointment, it doesn't check to see if the inputted strings are equivalent to any of the acceptable ones (in the lists days_labels and times labels). Instead it just accepts any second random input to be correct as shown:
Welcome to the acupuncture booking system.
What day would you like your appointment? s
Invalid entry. Please enter a valid day: z
What time would you like your appointment? d
Invalid entry. Please enter a valid day: f
---------------------------------
Did you want to book more appointments (type n for no, any other key for yes)?
What needs to be done in order to have the function check to see if the inputted strings correspond with any of the strings in the days_labels and times_labels lists in order for the user to "book" an appointment?
So you wont to create a function to check if any inputted string have been already used.
There reason your code isnt working correctly is because you tried to check wherethere your counter is up to 3, while it isnt any loop, and thus it only ascends to 1.
To re-arrange that to a correct way for example, you would do this:
while answer not in possible_values:
<your code here>
I didn't test this at all but it should be enough to guide you to fix your incrementing error.
def isValidDayInput(input):
accept = false
# your code here
return accept
def dayInput(count, maxAttempts):
waiting = true
while (waiting && count <= maxAttempts):
answer = promptForInput()
if (isValidDayInput(answer)): # accept returned true during validation
waiting = false # answer is valid so jump out loop
else(): # accept returned false during validation
count += 1
if (!waiting && count == maxAttempts):
print("Too many incorrect attempts. Exit")
else:
print("thank you")

Manipulating Strings to return concatenated username

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

Python: Error passing user inputed variables between functions

I am currently trying to build a simple ATM program(text based) from scratch. My problem is passing the user inputed variables between functions. The error I'm getting is ( init() takes exactly 3 arguments (1 given) ). Could someone explain what is happening and what I'm doing wrong?
class Atm:
acctPass = 0
acctID = 0
def __init__(self, acctID, acctPass):
#self.acctName = acctName
#self.acctBal = acctBal
self.acctPass = acctPin
self.acctID = acctID
def greetMenu(self, acctID, acctPass):
while acctPass == 0 or acctID == 0:
print "Please enter a password and your account number to proceed: "
acctpass = raw_input("Password: ")
acctID = raw_input("Account Number: ")
foo.mainMenu()
return acctPass, acctID # first step to transfer data between two functions
def mainMenu(self, acctID, acctPass):
print ""
acctpass = foo.preMenu(acctPass, acctID)
print acctPass
print "Made it accross!"
def deposit():
pass
def withdrawl():
pass
foo = Atm()
foo.greetMenu()
foo = Atm()
passes exactly 1 argument to Atm.__init__ -- the implicit self. The other two arguments (acctId and acctPass) are missing so python complains.
It looks to me like you can get rid of __init__ all together and bind the instance attributes in greetMenu:
class Atm:
acctPass = 0
acctID = 0
def greetMenu(self):
while self.acctPass == 0 or self.acctID == 0:
print "Please enter a password and your account number to proceed: "
self.acctpass = raw_input("Password: ")
self.acctID = int(raw_input("Account Number: "))
self.mainMenu()
# etc.
Here you'll still probably need to mess with mainMenu a bit to get it working (note now we're not passing the arguments around via function call arguments -- The values are stored on the class).
Thats the constructor called with foo = ATM()
def __init__(self, acctID=0, acctPass=0):
adding the =0 to the parameters initializes them to 0
and you have now overrode the constructor to accept 1,2 or 3 values.
in the greetmenu
def greetMenu(self, acctID, acctPass):
while acctPass == 0 or acctID == 0:
print "Please enter a password and your account number to proceed: "
acctpass = raw_input("Password: ")
acctID = raw_input("Account Number: ")
foo.mainMenu()
return acctPass, acctID # first step to transfer data between two functions
you need to either send in the parameters to the function ATM.greetmenu(1234,'pwd') or use the ones defined in the class like this.
def greetMenu(self):
while self.acctPass == 0 or self.acctID == 0:
print "Please enter a password and your account number to proceed: "
self.acctpass = raw_input("Password: ")
self.acctID = raw_input("Account Number: ")
foo.mainMenu()
#return acctPass, acctID # first step to transfer data between two functions

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

python: global name 'user_input' is not defined

I keep getting the error message "global name 'user_input' not defined. new to python and to SO, hope you can help. Here's my code. Sorry if it's a mess. just starting out and teaching myself...
def menu():
'''list of options of unit types to have converted for the user
ex:
>>> _1)Length
_2)Tempurature
_3)Volume
'''
print('_1)Length\n' '_2)Temperature\n' '_3)Volume\n' '_4)Mass\n' '_5)Area\n'
'_6)Time\n' '_7)Speed\n' '_8)Digital Storage\n')
ask_user()
sub_menu(user_input)
def ask_user():
''' asks the user what units they would like converted
ex:
>>> what units do you need to convert? meter, feet
>>> 3.281
'''
user_input = input("Make a selection: ")
print ("you entered", user_input)
#conversion(user_input)
return user_input
def convert_meters_to_feet(num):
'''converts a user determined ammount of meters into feet
ex:
>>> convert_meters_to_feet(50)
>>> 164.042
'''
num_feet = num * 3.28084
print(num_feet)
def convert_fahrenheit_to_celsius(num):
'''converts a user determined temperature in fahrenheit to celsius
ex:
>>> convert_fahrenheit_to_celsius(60)
>>> 15.6
>>> convert_fahrenheit_to_celsius(32)
>>> 0
'''
degree_celsius = (num - 32) * (5/9)
print(round(degree_celsius, 2))
def sub_menu(num):
'''routes the user from the main menu to a sub menu based on
their first selection'''
if user_input == '1':
print('_1)Kilometers\n' '_2)Meters\n' '_3)Centimeters\n' '_4)Millimeters\n'
'_5)Mile\n' '_6)Yard\n' '_7)Foot\n' '_8)Inch\n' '_9)Nautical Mile\n')
ask = input('Make a selection (starting unit)')
return
if user_input == '2':
print('_1)Fahrenheit\n' '_2)Celsius\n' '_3)Kelvin\n')
ask = input('Make a selection (starting unit)')
return
When you do:
user_input = input("Make a selection: ")
Inside the ask_user() function, you can only access user_input inside that function. It is a local variable, contained only in that scope.
If you want to access it elsewhere, you can globalise it:
global user_input
user_input = input("Make a selection: ")
I think what you were trying was to return the output and then use it. You kind of got it, but instead of ask_user(), you have to put the returned data into a variable. So:
user_input = ask_user()
THere's no need to globalise the variable (as I showed above) if you use this method.
In your menu function, change the line that says ask_user() to user_input = ask_user().

Categories