Unknown reason for code executing the way it does in python - python

I am a beginner programmer, using python on Mac.
I created a function as a part of a game which receives the player's input for the main character's name.
The code is:
import time
def newGameStep2():
print ' ****************************************** '
print '\nStep2\t\t\t\tCharacter Name'
print '\nChoose a name for your character. This cannot\n be changed during the game. Note that there\n are limitations upon the name.'
print '\nLimitations:\n\tYou cannot use:\n\tCommander\n\tLieutenant\n\tMajor\n\t\tas these are reserved.\n All unusual capitalisations will be removed.\n There is a two-word-limit on names.'
newStep2Choice = raw_input('>>>')
newStep2Choice = newStep2Choice.lower()
if 'commander' in newStep2Choice or 'lieutenant' in newStep2Choice or 'major' in newStep2Choice:
print 'You cannot use the terms \'commander\', \'lieutenant\' or \'major\' in the name. They are reserved.\n'
print
time.sleep(2)
newGameStep2()
else:
newStep2Choice = newStep2Choice.split(' ')
newStep2Choice = [newStep2Choice[0].capitalize(), newStep2Choice[1].capitalize()]
newStep2Choice = ' ' .join(newStep2Choice)
return newStep2Choice
myVar = newGameStep2()
print myVar
When I was testing, I inputted 'major a', and when it asked me to input another name, i inputted 'a b'.
However, when it returned the output of the function, it returns 'major a'. I went through this with a debugger, yet I still can't seem to find where the problem occurred.
Thanks for any help,
Jasper

Your recursive call to newGameStep2() isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and return newStep2Choice returns the first read value. You need to change the recursive call to:
return newGameStep2()

Related

Trying to get my python program to run but I keep getting a variable assignment error. Any ideas as to what I am doing wrong?

def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.

Why does my return statement ignore the rest of my code in a function in python?

In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.
def game():
#This selects 5 community cards from the pick_community function
community = pick_community(5)
card_4 = community[3]
card_5 = community[4]
first_3 = community[0:3]
return first_3
river = raw_input("If you are done with the round hit enter:" )
try:
if river =="":
return card_4
except:
print "Dont cheat man"
exit()
That:
return first_3
returns and therefore ends the function.
The remaining code is just ignored, because you will never get past the return.
Because a return statement gets out of the function, so the rest of the code wont execute
If you want to return first 3 values and then continue in code you can do it using yield. It basically inserts values into generator, then in the end return the whole generator.
https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/
more here, or google for even more :)

PDA (Permissible Dating Age) Algorithm?

The project is to create a simple Python program that will prompt the user for his or her age and then print out the lower and upper age limits for the user's date based on the Permissible Dating Age Algorithm.
The PDA Algorithm is: d = a/2 + 7, a is your age, and d is the lowest permissible age of your date where a is an integer.
Here is the code I have so far:
import random
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdoutflush()
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
It seems to be running okay, yet nothings printing out and I'm confused as to what's going wrong with the print statements.
You weren't that far off the mark to be honest but your print statements were not faulty. Rather, they are contained within a function that you never call so they never actually run. There is also a small typo. This code will run:
import random #Not needed with current code
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdout.flush() #You missed a full-stop
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
#Something to call your function and start it off
start_program = findACompanion()
Stick with the classes, it won't take long till it falls into place. Being thrown in at the deep-end is the best way :)
You've defined a function findACompanion, but nothing is calling the function, so none of the statements within the function are being executed. You can call it yourself from the prompt:
>>> findACompanion()
There's a convention that is common in Python to detect if you are running a file as your main program and to make the call automatically, see Top-level script environment. The convention calls for the function to be called main but you can call anything you'd like.
if __name__ == "__main__":
findACompanion()

NameError: global name 'PIN' is not defined

I am getting the following Error Message :
Traceback (most recent call last):
File "/Volumes/KINGSTON/Programming/Assignment.py", line 17, in <module>
Assignment()
File "/Volumes/KINGSTON/Programming/Assignment.py", line 3, in Assignment
My code is:
def Assignment():
prompt = 'What is your PIN?'
result = PIN
error = 'Incorrect, please try again'
retries = 2
while result == PIN:
ok = raw_input(Prompt)
if ok == 1234:
result = menu
else:
print error
retries = retries - 1
if retries < 0:
print 'You have used your maximum number of attempts. Goodbye.'
Assignment():
would really appreciate a little help if anyone knows where i am going wrong and can explain
That particular error is raised because when you say result = PIN, PIN doesn't actually exist. Since it isn't in quotes, Python assumes it is a variable name, but when it goes to check what that variable is equal to, it doesn't find anything and raises the NameError. When you fix that, it will also happen with prompt since you later refer to it as Prompt.
I'm not sure if this is your full code or not, so I'm not sure what the other issues could be, but it looks like you are using result and PIN to control your while loop. Remember that a while loop runs until the condition it is checking is False (or if you manually break out of it), so instead of declaring the extra variables, you could start with something like this:
def Assignment():
# No need to declare the other variables as they are only used once
tries = 2
# Go until tries == 0
while tries > 0:
ok = raw_input('What is your PIN?')
# Remember that the output of `raw_input` is a string, so either make your
# comparison value a string or your raw_input an int (here, 1234 is a string)
if ok == '1234':
# Here is another spot where you may hit an error if menu doesn't exist
result = menu
# Assuming that you can exit now, you use break
break
else:
print 'Incorrect, please try again'
# Little shortcut - you can rewrite tries = tries - 1 like this
tries -= 1
# I'll leave this for you to sort out, but do you want to show them both
# the 'Please try again' and the 'Maximum attempts' messages?
if tries == 0:
print 'You have used your maximum number of attempts. Goodbye.'

Learn Python the Hard Way Help: Exercise 13

I'm having trouble with the extra credit on Exercise 13 of Learn Python the Hard Way.
It wants me to combine argv with raw_input, which I can't figure out.
Could anyone help me out? Examples would be great!
Thanks so much!
Edit: The original code for the exercise is:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
an example would be indistinguishable from the answer, which is unlikely to be the best way to help you. perhaps you are overthinking the question, though. i believe the idea is to use some command-line input (which goes into argv) and some entered input (which comes through raw_input) to make a script which reports on both. For example, it might produce:
The script is called: ex13.py
Your first variable is: cheese
Your second variable is: apples
You entered the following data: foo bar baz
This is how I tried to do it:
from sys import argv
script, weather, feeling = argv
print "Hot or Cold",
weather = raw_input()
print "Happy or sad",
feeling = raw_input()
print "The name of the script is:" , script
print "The day is:", weather
print "Today I am feeling:", feeling
import sys
def main():
all_args = sys.argv[:]
user = None
while user != 'STOP':
user = raw_input('You have %d args stored. Enter STOP or add another: ' % len(all_args))
if user != 'STOP':
all_args.append(user)
print 'You entered %d args at the command line + %d args through raw_input: [%s]' % (len(sys.argv), len(all_args) - len(sys.argv), ', '.join(all_args))
if __name__ == '__main__':
main()
This was confusing to me as well. The author puts this in his faq at the bottom.
Q: I can't combine argv with raw_input().
A: Don't overthink it. Just slap two lines at the end of this script that uses raw_input() to get something and then print it. From that start playing with more ways to use both in the same script.
Here is how I solved this: (note: you still have to provide the arguments when initially running the script)
from sys import argv
script, first, second, third = (argv)
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
first = raw_input("\nNew First Variable? ")
second = raw_input("New Second Variable? ")
third = raw_input("New Last Variable? ")
print "\n\nYour new variables are %s, %s, and %s" % (first, second, third)
Here's the output I get:
C:\Users\mbowyer\Documents\Python_Work>python ex13a.py 1 2 3
The script is called: ex13a.py
Your first variable is: 1
Your second variable is: 2
Your third variable is: 3
New First Variable? a
New Second Variable? b
New Last Variable? c
Your new variables are a, b, and c
C:\Users\mbowyer\Documents\Python_Work>

Categories