Python Function variable: local and global - python

I am struggling with local and global variables.
I was doing this:
def SomeFunc(Input):
if Input == 1:
Input = "True"
elif Input == 0:
Input = "False"
RawInput=int(raw_input("Input 1 or 0: "))
SomeFunc(RawInput)
print str(RawInput)
and it showed this:
>>> def SomeFunc(Input):
if Input ==1:
Input = "True"
elif Input ==0:
Input = "False"
>>> RawInput = int(raw_input("Input 1 or 0: "))
Input 1 or 0: 1
>>> SomeFunc(RawInput)
>>> print str(RawInput)
1
What should I do so that the input will convert to str in the function?

Input is an int which is an immutable object. In other words, you can't change it anywhere. However, you can assign it to something else. One of the tricky things about python is learning that everything is just a reference. When you assign to something, you just change the reference. Think about your variables as strings which go into boxes. When you assign to a variable, you put that string in a particular box. When you assign that variable to something else, you change the box that string goes to. Of course, when you actually do an addition, you add the contents of the box, not the strings (which is a little confusing). If you're accustomed to programming in C, it's kind of like everything is a pointer which gets automatically dereferenced (except when you do an assignment).
So, what to do? The easiest thing is to return the value from your function.
def some_func(inpt):
if inpt == 1:
return "True"
elif inpt == 0:
return "False"
else:
raise ValueError("WHAT IS THIS GARBAGE? I SAID 0 OR 1!!!!") # ;^)
Now you can call your function as:
processed_input = some_func(rw_inpt)
as a side note, your function can be condensed to:
def some_func(inpt):
return str(bool(inpt))
or
def some_func(inpt):
return "True" if inpt else "False"
Both of these pass (and return "True" if the user puts in any integer that isn't 0). If you really want to force the user to not put in something like "2", you can do:
def some_func(inpt):
return {1:"True",0:"False"}[inpt]
But I wouldn't recommend that one...

Basically you want the argument to be pass-by-reference, but that is not how Python works for basic datatypes. The pythonic way of doing this is as following:
def some_func(input):
if input == 1:
return "True"
elif input == 0:
return "False"
And then
raw_input = some_func(raw_input)

Note: You can just do this: print bool(int(raw_input("Input 1 or 0: ")))
The more pythonic way of doing it would be as follows:
def some_func(x):
if x == 1:
return "True"
elif x == 0:
return "False"
x = int(raw_input("Input 1 or 0: "))
x = some_func(x)
print x
However if you did want to use globals you could do it like this but this is really hacky and it isn't one of the good coding practices that python promotes.
def some_func():
global x
if x == 1:
x = "True"
elif x == 0:
x = "False"
x = int(raw_input("Input 1 or 0: "))
some_func()
print x
Some other notes:
Try not to use names like the bultins eg. Input and RawInput since it makes things unclear and mixes everything up.

What should I do so that the input will convert to str in the
function?
def SomeFunc(Input):
as_string = str(Input)
if Input == '1':
Input = "True"
elif Input == '0':
Input = "False"
Note that python has a native boolean type, including the values True and False already. You can use the integer value of Input as a condition all on its own.

Related

Calling function to new function in Python

I have tried this several different ways, I am still fairly new to Python so go easy on me. I am trying to execute a script where the user can choose to import a list from a plaintext file, or input a list manually, and the script will return the median and mode of the data.
The problem I am having is that my median and mode functions are not recognizing the reference to the raw data, and the main function isn't recognizing the median and mode from their respective functions.
I guess it's safe to say I am not calling these functions correctly, but frankly I just dont know how. Any help here would be much appreciated.
def choice():
##Choose user input type
start = input("Please select your input method by typing 'file' or 'manual' in all lower-case letters: ")
# Import File Type
userData = []
if start == "file":
fileName = input("Please enter the file name with the file's extension, e.g. ' numbers.txt': ")
userData = open(fileName).read().splitlines()
return userData
userData.close()
# Manual Entry Type
elif start == "manual":
while True:
data = float(input("Please enter your manual data one item at a time, press enter twice to continue: "))
if data == "":
break
userData = data
return userData
# Error
else:
print("You have entered incorrectly, please restart program")
def median(medianData):
numbers = []
for line in (choice(userData)):
listData = line.split()
for word in listData:
numbers.append(float(word))
# Sort the list and print the number at its midpoint
numbers.sort()
midpoint = len(numbers) // 2
print("The median is", end=" ")
if len(numbers) % 2 == 1:
medianData = (numbers[midpoint])
return medianData
else:
medianData = ((numbers[midpoint] + numbers[midpoint - 1]) / 2)
return medianData
def mode(modeData):
words = []
for line in (choice(userData)):
wordsInLine = line.split()
for word in wordsInLine:
words.append(word.upper())
theDictionary = {}
for word in words:
number = theDictionary.get(word, None)
if number == None:
theDictionary[word] = 1
else:
theDictionary[word] = number + 1
theMaximum = max(theDictionary.values())
for key in theDictionary:
if theDictionary[key] == theMaximum:
theMaximum = modeData
break
return modeData
def main():
print("The median is", (median(medianData)))
print("The mode is", (mode(modeData)))
Welcome! I think you need to read up a bit more on how functions work. The argument when you define a function is a "dummy" local variable whose name matters only in the definition of a function. You need to supply it a variable or constant whose name makes sense where you use it. It is a very good analogy to functions in mathematics which you may have learned about in school. (Note that these points are not specific to python, although the detailed syntax is.)
So when you have def median(medianData) you need to use medianData in the definition of the function, not userData, and when you call median(somevar) you have to make sure that somevar has a value at that point in your program.
As a simpler example:
def doubleMyVariable(x):
return 2*x
How would you use this? You could just put this somewhere in your code:
print(doubleMyVariable(3))
which should print out 6.
Or this:
z = 12
y = doubleMyVariable(z)
print(y)
which will print 12.
You could even do
z = 36
x = doubleMyVariable(z)
which will assign 72 to the variable x. But do you see how I used x there? It has nothing to do with the x in the definition of the function.

If loop does not take correct judgement based on variable type

In the code below, if loop does not take the condition (of true) and instead goes to the elif statement. I am trying to use if statement to control what could go into a list and what can not :
average = []
def judge(result):
try:
float(result)
return True
except ValueError:
return 'please type number'
list_in = input('Type in your number,type y when finished.\n')
judge_result = judge(list_in)
if judge_result:
aver_trac = aver_trac + 1
average.append(list_in)
print('success')
elif isinstance(judge_result, str):
print(judge_result)
However if I specify
if judge_result == True:
then this if loop will work
Python evaluates non empty strings as True, and empty strings as False.
In your case, the judge function returns either True, or a non empty string, which is also True; When you evaluate the return, if judge_result: is always True.
The fact that if judge_result == True: works, is a great example of the difference between == and is in python
with all that said, the way you approach the input of your data is a bit awkward; you could do something like this instead:
average = []
while True:
list_in = input('Type in your number,type y when finished.\n')
if list_in == 'y':
break
try:
average.append(float(list_in))
except ValueError:
print('please type number')

Can't figure out how to make my funtion not return None in Python

I have a program I am trying to make which will either show all the factors of a number or say it is prime. It's a simple program but I have one main issue. Once it prints all of the factors of an inputted number, it always returns none. I have tried multiple ways to get rid of it but nothing works without screwing something else up. The code is below.
def mys(x):
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
print(mys(x))
That code is just for printing the factors but that is where the problem lies. The results I get after entering a number, in this case 20, are as follows:
2
4
5
10
None
No matter what I do, I can't get the None to not print.
So if you don't want the return value of mys (None) not printed, then don't print it:
mys(x)
In python, a function that has no return statement always returns None.
I guess what you are trying to do is calling the mys function, and not printing it.
Note that you should remove x parameter, because it is asked inside of the function.
def mys():
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
mys()
It would be better not to include user input and printing in your function. It would make it easier to test and to reuse:
def mys(x):
result = []
for i in range(2,x):
r = x % i
if r == 0:
result.append(i)
return result
x = input("Enter a number: ")
print(mys(x))

Python - Function calling problems

I just started learning python 2 days ago and Im trying to make some kind of text based adventure to practice , the only problem Im having is with functions:
def menu_op():
print('1- Action 1')
print('2- Action 2')
choice= input('Choose action: ')
return choice
def action_op(x):
if x == 1:
print('You chose action 1')
if x == 2:
print('You chose action 2')
menu_op()
action_op(menu_op())
The idea behind this is to call the menu function , which gives a value equal to user's input , which gets fed into the action function when the latter is called and does something depending on the user choice.
Cant tell what im doing wrong though , as the code doesnt seem to work.
Thanks in advance
It looks like you are using Python 3.x. In that version, input returns a string object like raw_input did in Python 2.x. This means that the return value of the function menu_op will always be a string.
Because of this, you need to compare x with strings rather than integers:
if x == '1':
print('You chose action 1')
elif x == '2':
print('You chose action 2')
I also changed the second if to elif since x could never equal both '1' and '2'.
You're calling menu_op() function twice. The first time it gets called choice is not passed to action_op()
menu_op() #return is not catched
action_op(menu_op())
And the value returned from menu_op is a string so you should compare strings in action_op instead of comparing x with integers
def action_op(x):
if x == 1:
^^^ #should compare strings here -> x == "1"
choice= int(input('Choose action: ')) # make choice an int to compare
In [1]: 1 == "1"
Out[1]: False
In [2]: 1 == int("1")
Out[2]: True
input is a string and you are comparing if x == 1 where x is "1"

Printing with Quotes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How come when I use the program below i keep getting "y" in quotes opposed to the value defined by y, which would be the string entered by the user
def main():
x = (input("Give me a boolean: ").lower() == 'true')
y = str(input("Give me a string: "))
z = int(input("Give me a number: "))
if x == True:
print (y)
print ("\"",y,"\"",sep="")
else:
print (z*2)
main()
Let's talk about booleans, because this is actually the problem here.
x = bool(input("Give me a boolean: "))
# x is ALWAYS True unless the user enters an empty string
The problem here is that all non-empty strings are boolean True. "Hello" is True, "TRUE" is True, and "False" is True. The only string that evaluates to False is "". So when you prompt for input here, then test it later, you're always going to pass that test unless the user just bypasses the test. Let's move on...
y = str(input("Give me a string: ")) # good here, though no need to call str()
z = int(input("Give me a number: ")) # uh oh...
If I enter ajkldfj for z, it will throw a ValueError. The usual way to handle this is try/except, e.g.:
z = input("Give me a number: ")
try:
int(z)
except ValueError as e:
# handle it
Next up...
if x == True or true:
This is the same issue that TONS of people have. if foo == 1 or 2 doesn't mean what you think it does, it actually means if (foo == 1 is True) or (2 is True). To do what you're trying to do, you should do if x == "True" or x == "true", but better is if x.lower() == "true" and better still is if x.casefold() == 'true' but BEST YET is just if x. Remember, you're already turning it into a bool when you prompt for it. You can change that of course by dropping the bool() call, then testing for it here, in which case I recommend if x.lower() == 'true' or if x.casefold() == 'true'. The other code you'll see quite often is if x in ('true','True'), but since we can just lowercase to remove all ambiguity: DO IT!
Now to your print statements:
print (y) # prints the value in y
print ('"y"') # prints "y"
If this isn't what you want to do, you can use string formatting or really any of a bazillion other things to format it correctly. Let me know what you want to do and we can talk further!
you must use below line for print only y
print(y)
and below for y with Parentheses
print( "(" + y + ")")
Warning:in your Code if X==False then python give you below error
NameError: name 'true' is not defined
You can use format alongside print.
print("({0})".format(y))
Where 0 references the first argument passed to format, 1 the second, and so on. Also, you're doing x == True or true, the or true is wrong and should be removed. Also bool("True") == bool("False") == True, since strings (of length > 0) are True in Python, you probably want something like
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
Edit: Sample session
>>> def main():
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
>>> main()
True/False? false
Input string: dog
Number: 2
>>> main()
True/False? true
Input string: dog
Number: 2
(dog)

Categories