python change global string in function - python

First off i am very new to coding and python. I am trying to call a global string inside of a function. Then I want to change it into an integer. Next, I want to apply some Math to the integer. Finally I want to convert that integer back to a string and send it back to the global to use in other functions.
I have accomplished most of what I needed to do, but I am having trouble sending the string back to the global. I have tried using return() but it just quits the program. Instead I want it to go to another function, while retaining the new value
Relevant code
current_gold = '10'
def town():
global current_gold
print(current_gold)
def pockets():
global current_gold
new_gold = int(current_gold) + 5
new_gold = str(new_gold)
print(new_gold.zfill(3))
input("\tPress Enter to return to town")
town()
This is not the full code. I maybe doing stuff drastically wrong though.

current_gold = '10'
def changeToInt():
global current_gold
current_gold = int(current_gold)
print(type(current_gold)) # It's a string right now
changeToInt() # Call our function
print(type(current_gold)) # It's an integer now
Or you could do it by passing a parameter to your function like so:
current_gold = '10'
def changeToInt2(aVariable):
return int(aVariable)
print(type(current_gold)) # It's a string right now
current_gold = changeToInt2(current_gold) # make current_gold the output of our function when called with current_gold as aVariable
print(type(current_gold)) # It's an int now

Related

How can I get a function in Python 3 to return a value that I can use in another function?

I need to design a game of snakes and ladders in python and for part of it, I need to be able to roll a dice and get a random value. For this, I have imported random and then written the function below. However, obviously, I then need to be able to use the dice value in other functions of the game. How do I get it so that the value python returns is retained and able to be used in another function.
Below is the function I have written for rolling the dice. However, when I then run this function and then afterwards try print(dice_value), the program tells me that dice_value has not be defined.
Anybody able to help??
import random
def roll_dice():
dice_value = random.randint(1,6)
print("Its a..." + str(dice_value))
return dice_value
The variable dice_value exists only inside your function roll_dice(). It is a local variable.
You need to call your function with:
my_variable = roll_dice()
Now the result of your function is stored in the variable my_variable, and you can print it.
You have to save the return value somewhere and then use it or pass it to another function.
For example:
>>> import random
>>> def roll_dice():
... dice_value = random.randint(1,6)
... print("[in roll_dice] Its a..." + str(dice_value))
... return dice_value
...
>>> obtained_dice = roll_dice()
[in roll_dice] Its a...1
>>> print("[outside roll_dice] Its a..." + str(obtained_dice))
[outside roll_dice] Its a...1
variable dice_value is a local variable inside the function space so you have to return and save it in another variable to continue using it
You can store the return value of your function roll_dice() in a variable that will in return store the value of the return variable (dice_value).
random_dice_value = roll_dice()
Note: You need to call the function after you have implemented it since Python is an interpreter language. It will execute the file line by line.
The problem is that you're trying to call the variable dice_value outside of its scope. If you still go on with your one liner print statement, you can do so by calling the function (that's returning the dice_value variable) as in:
print(roll_dice())

how to access a variable that's inside a function [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 8 months ago.
I'm trying to do 4 steps where I ask the user for a "key character" and a string, then capitalize the string, then remove all instances of the key character from the string. Each of these steps is supposed to be its own function. However, steps 3 and 4 rely on accessing variables located in the functions from steps 1 and 2.
I've read a few threads on this such as the following...
How to access the variables declared inside functions in python
...which suggests you must "return" the variables after defining them, but I've done that (I think) and it hasn't changed anything.
def main():
get_key_character()
get_string()
sentence_capitalizer()
remove_key_character()
def get_key_character():
key_character=str(input("Please enter a SINGLE character to act as key? "))
if len(key_character)!=1:
get_key_character()
else:
return key_character
def get_string():
phrase_input=str(input("Please enter a phrase or sentence >=4 and <=500 characters: "))
if len(phrase_input) <4 or len(phrase_input)>500:
get_string()
else:
return phrase_input
def sentence_capitalizer():
import re
sentence_capitalized=(re.sub(r"(^|\?|\.|\!)\s*(\w)", lambda q: q[0].upper(), phrase_input))
return sentence_capitalized
def remove_key_character():
sentence_capitalized.replace(key_character, "")
main()
error: undefined name phrase_input in def sentence_capitalizer and undefined name key_character in def remove_key_character
What you are missing is that the returned value must be stored in another variable.
For example,
def test():
x = 1
return x
def main():
z = test()
print(z)
main()
This program will output:
1
You must pass the output of your functions as parameters to the subsequent calls of different functions. I have reworked your code to work like this.
def main():
key_character = get_key_character()
phrase_input = get_string()
sentence_capitalized = sentence_capitalizer(phrase_input)
removed = remove_key_character(key_character, sentence_capitalized)
print(removed)
def get_key_character():
key_character=""
while len(key_character) < 1:
key_character=str(input("Please enter a SINGLE character to act as key? "))
return key_character
def get_string():
phrase_input=str(input("Please enter a phrase or sentence >=4 and <=500 characters: "))
if len(phrase_input) <4 or len(phrase_input)>500:
get_string()
else:
return phrase_input
def sentence_capitalizer(phrase_input):
import re
sentence_capitalized=(re.sub(r"(^|\?|\.|\!)\s*(\w)", lambda q: q[0].upper(), phrase_input))
return sentence_capitalized
def remove_key_character(key_character, sentence_capitalized):
return sentence_capitalized.replace(key_character, "")
main()
if len(key_character)!=1:
get_key_character()
Your function does not return anything (so implicitly returns None) in this case. You want to return get_key_character() (or perhaps more usefully refactor to avoid recursion, i.e. add a while loop and exit it when you receive a valid character, rather than have the function call itself until it receives a valid character).
More generally, you should avoid global variables. Every time a function returns something useful, the calling code should assign that value to a local variable. If you need to pass that value to another function, make that function accept a parameter into another local variable of its own.

Function not returning random integer for variable

I have a very simple problem, when I run the following code:
from random import randint
def create_random():
x = random.randint(1,4)
return x
print(create_random)
The output comes to this:
< function create_random at 0x7f5994bd4f28 >
Note: every character between "0x7f" and "f28" are random each time the code is run.
My goal was to be able to call the function multiple times with x being assigned a new integer value between 1 and 3 with each invocation.
You aren't actually calling the function. To do this you need to do:
print(create_random())
Just now you're printing the reference to the function which isn't very helpful for you in this case.
You have to call the function, like:
print(create_random())
Also in the function, this line:
x = random.randint(1,4)
Should be just:
x = randint(1,4)
Since you did a from ... import ... statement.
your last line does not do anything, since you want it to print 'create_random' that is not a variable. if you want to call a function, it has to have (). So, you should call it and put it in the print function:
print(create_random())

How to change a variable and keep the change from a function inside a function

#a test to see how to call and modify a variable by a function inside a function!
test_variable = "Hello __1__ !!, I'm good, How about you!!"
#function 1 to save to variable
def test_function_1():
global test_variable
hello = test_variable
return hello
#function 2 to use the variable through function 1
def test_function_2(test):
global test_variable
word = raw_input("Hi, Enter your word\n")
print
test = test.replace("__1__", word)
return test
#See how the function work!
print test_function_2(test_function_1())
#See if the variable changed by the function or not!
print test_variable
I can't keep the change to the variable. I try global in every function and it didn't work.
Remember in python, strings are immutable. So you can't change them. (I am guessing by 'I can't keep the change to a variable', you were expecting the global test_variable to change as well.
You are essentially assigning names. This talk is a good place to start to understand some core python concepts:
https://www.youtube.com/watch?v=_AEJHKGk9ns

How to use counter variable inside the body of recursive function

Below the code for counting the no of '1' character in String.
count2=0 #global variable
def Ones(s):
no=0;
global count2 #wanted to eliminate global variable
if(count2>=len(s)):
return no
if(s[count2]=='1'):#count2 is the index of current character in String
no = no+1
count2=count2+1
return no + Ones(s)
else:
count2=count2+1
return Ones(s)
in the above code using count2 as a global variable , is there any possible way to declare and use count2 variable as a local inside the function , have tried like but no luck
def Ones(s):
count2=0 # but everytime it get reset to zero
Note: number of parameter of function should be remain only one and no any other helper function have to use.
The avoidance of explicit state variables is an important part of the recursion concept.
The method you are calling only needs the remainder of the string to find 1s in it. So instead of passing a string, and the position in the string, you can pass only the remainder of the string.
Python's powerful indexing syntax makes this very easy. Just look at it this way: Each instance of the method can take away the part it processed (in this case: one character), passing on the part it didn't process (the rest of the string).
Just like #ypnos said, if you really want to use recursion, here is the code:
def Ones(s):
if not s:
return 0
if s[0]=='1':
return 1 + Ones(s[1:])
else:
return Ones(s[1:])
Hope it helps.

Categories

Resources