Python 3x Function runs without being called - python

here is My code
code
__author__ = 'Jared Reabow'
__name__ = 'Assignment 2 Dice game'
#Date created: 14/11/2014
#Date modified 17/11/2014
#Purpose: A game to get the highest score by rolling 5 virtual dice.
import random
#pre defined variables
NumberOfDice = 5 #this variable defined how many dice are to be rolled
def rollDice(NumberOfDice):
dice = [] #this is the creation of an unlimited array (list), it containes the values of the 5 rolled dice.
RunCount1 = 1 #This defines the number of times the first while loop has run
while RunCount1 <= NumberOfDice:
#print("this loop has run " , RunCount1 , " cycles.") #this is some debugging to make sure how many time the loop has run
TempArrayHolder = random.randint(1,6) #This holds the random digit one at a time for each of the dice in the dice Array.
dice.append(TempArrayHolder) #this takes the TempArrayHolder value and feeds it into the array called dice.
RunCount1 += 1 #this counts up each time the while loop is run.
return dice
rollDice(NumberOfDice)
dice = rollDice(NumberOfDice)
print(dice,"debug") #Debug to output dice array in order to confirm it is functioning
def countVals(dice,NumberOfDice):
totals = [0]*6 #this is the creation of a array(list) to count the number of times, number 1-6 are rolled
#print(dice, "debug CountVals function")
SubRunCount = 0
while SubRunCount < NumberOfDice:
totals[dice[SubRunCount -1] -1] += 1 #this is the key line for totals, it takes the dice value -1(to d eal with starting at 0) and uses it
#to define the array position in totals where 1 is then added.
#print(totals)
SubRunCount += 1
return totals
countVals(dice,NumberOfDice)
totals = countVals(dice,NumberOfDice)
print("totals = ",totals)
The indentation may be a bit wrong, I am new to stackoverflow.
My issue as stated in the title is that both functions will run regardless of being called or not, but they will run twice if called.
I read somewhere that removing the brackets from:
dice = rollDice(NumberOfDice)
so that it is this
dice = rollDice
would fix the issue, and to some extent it does something but not what I want.
if I do the above,it outputs
<function rollDice at 0x00000000022ACBF8> debug
rather than running the function, so I am left very stuck.
I would appreciate detailed explanation as to what is happening?
Update: I had called the function twice by mistake.
I thought I needed to run it before i could use its returned output, but no it will when whenever used in the code.

You do call rollDice() twice:
rollDice(NumberOfDice)
dice = rollDice(NumberOfDice)
The first time you ignore the return value, so you can just remove that call.
You do the same with countVals:
countVals(dice,NumberOfDice)
totals = countVals(dice,NumberOfDice)
Again, that's two calls, not one, and the first one ignores the return value; just remove those lines altogether.

Related

Initializing and displaying grid - python

I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())
You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.

dont know how to update score in python

So I'm in an intro to programming class and I need help updating the score in my "text based adventure game". What happens is you press enter, then a text appears (ex, you walk to the plane to find a monkey), then it says "Your score is 5". I want it so every time I press enter, the text appears and then my score goes up by 5. I spent a couple hours reading through my textbook and I don't know what to do. Everything is fine except the showScore function since it keeps printing my score as 5 after every step.
This is an example of the code:
def promptUser():
input("\n<Press Enter to continue...>\n")
def base():
print("You approach the base with friends")
def showScore():
x = 0
score = x + 5
print("Your score is now" ,score,)
I'm not a python programmer but I came across you post while doing some peer review for first timers questions and I thought I could help. Global Variables is what will solve your issue and based on this Python Global Variabl explaination the following should work for you.
score = 0
def promptUser():
input("\n<Press Enter to continue...>\n")
def shelter():
print("You approach the base with friends")
def showScore():
score = score + 5
print("Your score is now" ,score)
Currently you are defining your the variable 'x' within the showScore() function which means each time you call that function you are resetting x to zero before you add 5. In my solution, I define score as a Global variable so that each time you call the showScore() function it accepts simply adds 5 to score and then saves that in memory as the new score before displaying the score.
This may work for your current problem but in the real world it would be better to have a function that is dedicated to changing the score that is separate from the function that displays the score.
Hope this helps.
Try using:
def showScore():
score = 0
score = score + 5
print('Your score is now',score)
did you try putting score = 0 before the function then putting global score before score = score +5?

Conditionally increase integer count with an if statement in python

I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on.
I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement.
n = 0
print(n)
if True:
n += 1
Based on the comments of the previous answer, do you want something like this:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
EDIT:
Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable n to persist (Or keep it's new modified value) between multiple runs times.
So the code for that goes as(Assuming Python3.x):
try:
file = open('count.txt','r')
n = int(file.read())
file.close()
except IOError:
file = open('count.txt','w')
file.write('1')
file.close()
n = 1
print(n)
n += 1
with open('count.txt','w') as file:
file.write(str(n))
print("Now the variable n persists and is incremented every time.")
#Do what you want to do further, the value of n will increase every time you run the program
NOTE:
There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.
If you want it to work with if statement only. I think you need to put in a function and make to call itself which we would call it recursion.
def increment():
n=0
if True:
n+=1
print(n)
increment()
increment()
Note: in this solution, it would run infinitely.
Also you can use while loop or for loop as well.
When you rerun a program, all data stored in memory is reset. You need to save the variable somewhere outside of the program, on disk.
for an example see How to increment variable every time script is run in Python?
ps. Nowadays you can simply do += with a bool:
a = 1
b = True
a += b # a will be 2

Can variables retain previous values in a while loop in python? [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 6 years ago.
My question is when we use a variable in a while loop before changing the variable we have it assigned to (i.e on the Right hand side of the equal to) why does this new variable we supposedly assigned the next variables previous value to change?
I realise the phrasing of my question isn't entirely spot on, so in laymans terms, in my program i'm writing a variable called predispto disp before I change the value of displater in the while loop. Here i'm assuming all the code in python runs from top to bottom.
So here's an example of what value predisp holds
so if disp = ['_','_']
predisp = ['_','_']
which is fine.
But the moment I enter a letter as part of my hangman guess
the value of disp becomes ['u','_']
but the problem is predisp also becomes ['u','_'] which is not what I want. I want it to always have the previous value of disp before it undergoes any changes. I'm new to python so I don't really understand how all the variables work, i'm more used to them in C++. Here's the code (it's for a simple hangman game i'm writing).
# Created by Zur-en-Arrh
import random # Useful to select a topic from the file.
# Functions
def same_letter(user_letter, word_to_guess):
if user_letter == word_to_guess:
return True
else:
return False
def wrong_guess(prevdisp,currdisp):
if prevdisp == currdisp:
return True
else:
return False
# Dealing with the file.
filename = input("Which file do you want to play with ")
topics = str(open(filename, 'r').read())
list_of_topics = topics.split() # This is the list that contains the topics randomly selected from the file.
guess_me = list(list_of_topics[random.randint(0, len(list_of_topics) - 1)]) # This is what the user will need to figure out.
# Printing out the Dashes for the user.
disp = []
for i in range(0, len(guess_me)):
disp.append("_")
# This is just the declaration of the number of wrong guesses. This'll always be 0 at the start of the game.
wrong_guesses = 0
# While loop for game. Also note in hangman, you're only allowed 5 wrong guesses till the body is complete.
while wrong_guesses < 6:
print(' '.join(disp)) # Prints the game in an acceptable format to the user.
predisp = disp
if disp == guess_me: # end the game when the user wins.
break
user_guess = str(input("Which letter do you think will there be? "))
for i in range(len(guess_me)):
if same_letter(user_guess, guess_me[i]):
disp[i] = user_guess
print(predisp)
if wrong_guess(predisp, disp):
wrong_guesses += 1
if wrong_guesses == 6:
print("You got hung! Better luck next time")
break
if wrong_guesses < 6:
print("Well Done you won the game!")
In Python, variables are references to objects:
disp = []
creates a new list object and makes it accessible by the name disp. What it really does is set disp to point to the newly created list object. The assignment statement
predisp = disp
does the same thing, i.e. it sets predisp to reference the same list object as disp. Thus any change applied to the object that disp points to is also visible in the object that predisp points to - it's the very same object.
One way to avoid this is to create a copy on assignment:
predisp = disp[:]
This can be easily verified by using the id function:
disp = ['_'] * 3
predisp = disp
id(disp), id(predisp)
# same object ids for both variables
=> (4303250784, 4303250784)
predisp = disp[:]
id(disp), id(predisp)
# different object ids
=> (4303250784, 4303043832)

Combining functions in one file

infilehandle = open ("receipts-10-28-13.txt", "r")
# FUNCTIONS
def stripsigns( astring ):
"""Remove dollar signs"""
signs = "$"
nosigns = ""
for numbers in astring:
if numbers not in signs:
nosigns = nosigns + numbers
return nosigns
def totaltake():
"""Calculate total take"""
total = 0
for line in infilehandle:
values = line.split(':')
cardnumbers = values[1]
cardnumbers = stripsigns(cardnumbers)
total = (total + eval(cardnumbers))
total = round(total,2)
return total
# more code etc
def computetax(rate, total):
total = totaltake() - totaltip()
taxed = total * rate
taxed = round(taxed,2)
return taxed
# more code etc
# VARS
total = totaltake()
tips = totaltip()
tax = computetax(rate,total)
rate = eval(input("Input the tax rate as an integer:"))
# PRINT
print("Total take: $", totaltake())
print("Total tips: $", totaltips())
print("Tax owed: $", computetax(rate,total))
I'm trying to make a file that will look at elements from a txt file and then calculate things based on the numbers in the file. The functions are all either variations of the totaltake(), which is getting numbers from the file and finding the sum, or the computetax(), which takes the numbers the other functions calculate and multiplies/divides/etc. I've tested all the functions individually and they all work, but when I try to put them together in one file, it doesn't give me the output I want, and I don't know why. It prints the value of whatever is first in the vars list, and 0 for everything else -- so for the version of code I have above, it prints
Total take: $ 6533.47
Total tips: $ 0
Tax owed: $ 0
So basically, what am I doing wrong?
See Is file object in python an iterable
File objects are iterators, meaning that once a file has been iterated to completion, you cannot iterate over the file again unless it has been reset to the beginning of the file by calling file.seek(0).
When you only call totaltake(), because infilehandle has not yet been iterated, the for loop goes through all the lines in infilehandle, which is why you get the expected result.
However, when you put computetax() together with totaltake(), totaltake() gets called by itself, and then again incomputetax(). Because infilehandle has been iterated to completion the first time totaltake() is called, the for loop is not entered the second time and the initial value for total, 0, is returned.
As the value returned by totaltake() should not change, you should modify computetax() so that you can pass total as a parameter instead of calling totaltake(). You should do the same so that it also takes tips as a parameter instead of recalculating the value.
If you cannot modify computetake(), you could also seek to the beginning of infilehandle by adding infilehandle.seek(0) to the beginning of totaltake(), to allow it to be iterated again.

Categories