Program closing when it shouldn't - python

I'm makeing a text based game.
the user is asked to enter:
name
difficulty
skill level
However, once the user inputs the difficulty the program closes.
Any help will be appreciated.
OH AND PLEASE COULD YOU NOT JUST DOWN-VOTE WITHOUT GIVING AN EXPLANATION, NOT EVERYONE IS A PYTHON MASTER.
P.S. sorry for broken english
while True:
print("Welcome to 'The imposible quest'")
print("""
""")
name_charter = str(input("What's your name adventurer? "))
difficulty = str(input("Please choose the difficulty level(easy, normal, hard): "))
while set_difficulty==0:
if difficulty=="easy":
max_skill_start = 35
player_max_hp = 120
set_difficulty = 1
elif difficulty=="normal":
max_skill_start = 30
player_max_hp = 100
set_difficulty = 1
elif difficulty=="hard":
max_skill_start = 25
player_max_hp = 80
set_difficulty = 1
else:
print("ERROR, the option you chose is not a valid difficulty!")
print("Hello" + nam_char + "/n /n Please choose your abilities, keep in mind that you can't spend more than" + max_skill_start + "points in your habilities: ")
strength, dexterity, intelligence, perception, charm, combat, crafting, tradeing = input("Strength: "), input("Dexterity: "), input("Intelligence: "), input("Perception: "), input("Charm: "), input("Combat: "), input("Crafting: "), input("Tradeing: ")
end_prg = str(input("Do you want to close the program(yes/no)? "))
if end_prg=="yes":
quit()
elif end_prg=="no":
print("""
""")

You just need to set the set_difficulty to 0 before the while loop. Also I see you are printing out big empty lines, you can also use the print("\n") this will create a newline. You can add multiple by *by number desired :
print("\n"*10) //prints out 10 newlines.

Related

Save a variable from a function to reuse when it loops

I just started to learn python yesterday so complete noob. I have about 10 hours javascript experience to but had to switch since I'm learning Python in college. I decided to try make a program by myself since I learn a lot better doing that instead of countless videos.
The major problem I'm having is saving my variable of balance. When I win or lose the balance just restarts at 2000. I think that's probably because of the variable balance = 2000 but if I don't define it, it doesn't work. I know it's not anything important but I want to learn where I'm going wrong.
If anyone can help me that would be much appreciated. Also I know the codes a mess but will try make it better later.
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
if yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
playgame()
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
playgame()
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
playgame()
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
You can just pass balance as an argument, to your playgame function
like this
def playgame(balance=2000):
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
...
And than just pass, the new balance to all the playgame calls
But a much better way than using a recurent function would be a while loop
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame(balance=2000):
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
if yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
return balance
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
return balance
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
return balance
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
balance = playgame()
while input("You want to play again? Y/N").lower() == "y":
balance = playgame(balance)
else:
print ("Wrong Password " + name + " !")
Please note, that this code is not tested and may not work how you want.
Since balance is local to the function playgame() every time the function is called, the variable will be reset. You can fix this problem a couple of ways. You can make balance a global variable, or you can add a loop where the function doesn't return after one execution. The second example I gave would look something like this:
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
while yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
The first thing playgame does is set your balance to 2000, so it's always going to be 2000 at the beginning of a game. This is happening because you restart a new game by calling playgame() from within playgame. This is called recursion. It's a powerful tool that has a lot of uses, but this is probably not the best use of it. Among other things, when a game ends, it's going to return to where it was in the previous game, and pick up executing the next statement after playgame(). (You don't have anything like that in your current code, but the moment you do, you'll get confused. In short, playgame() is not a simple "go back to the beginning" command.)
So one way to address this is to change the main structure of your function to a loop. After balance = 2000 add:
while True:
and indent the rest of the function under that statement.
Wherever you have playgame() within the playgame function, change it to continue. This will cause the program to go back to the beginning of the while loop.
Since balance = 2000 is not within the loop, it will be executed once and will not be re-executed for subsequent games.
Another way to solve the problem (keeping the recursion) is to move the initialization of balance outside the loop, say to right after you ask for the user's name and password. In the playgame function, replace balance = 2000 with global balance. This way, the variable is not local to the function and will retain its value from call to call.
Finally, you could make the game a class rather than a standalone function. This way, balance can be an attribute of the object rather than a local variable to your function, but still not a global. (Global variables are generally a bad idea, especially as your code gets more complex, because they make it difficult to keep track of every piece of the data the function uses to do its job.) This is probably the best way to do it long-term, but you'll need to learn a bit more about programming before you tackle that.
Elaborating on loops since you said you are new to python, you can initiate the balance variable outside the function, and in a loop, you can ask for user input and call the function. Based on the input, you can rerun the function or exit and display balance.
One way would be, to modify you if-else loop for yesOrNo and add an elif (say elif yesOrNo=='end'), then break the loop and display balance.

Python user input (lists)

Hi again i was coding my text based game and came across another problem. My code:
print("\nPath 1 - bookkeeper", "\n Path 2 - mississippi", "\n Path 3 - sleeplessness", "\n Path 4 - keenness", "\n Path 5 - suddenness")
path_way = input("Scan the word you want by "
"\ntyping here to figure out the number associated "
"\nwith each letter to add them up : ")
foreign_lang = []
occurences = []
for character in path_way:
if character not in foreign_lang:
foreign_lang.append(character)
occurences.append(1)
else:
foreign_index = foreign_lang.index(character)
occurences[foreign_index] = occurences[foreign_index] + 1
for index in range(len(foreign_lang)):
print(foreign_lang[index], "-->", occurences[index])
print("Now that you added up you numbers use that number and")
while True:
try:
act_3 = int(input("Enter the number of henchmen you want to fight : "))
if act_3==8:
print("\n You easily fight the 8 henchmen and defeat them to proceed with the path!")
break
else:
print("Sorry you have been killed as the henchmen overwhelmed you as there were too many of them")
except:
print("Sorry you have been kicked from the agency for quitting on the mission")
So I want to lead the user back to the list question instead of the while loop question if they enter the wrong answer in the while loop question. Does anyone know how I can do it?
https://trinket.io/python3/6f8defd82c
If I am comprehending your question correctly, then you can simply create a function and call it in your while loop.
def func():
print("\nPath 1 - bookkeeper", "\n Path 2 - mississippi",
"\n Path 3 - sleeplessness", "\n Path 4 - keenness",
"\n Path 5 - suddenness")
path_way = input("Scan the word you want by "
"\ntyping here to figure out the number associated "
"\nwith each letter to add them up : ")
foreign_lang = []
occurences = []
for character in path_way:
if character not in foreign_lang:
foreign_lang.append(character)
occurences.append(1)
else:
foreign_index = foreign_lang.index(character)
occurences[foreign_index] = occurences[foreign_index] + 1
for index in range(len(foreign_lang)):
print(foreign_lang[index], "-->", occurences[index])
print("Now that you added up you numbers use that number and")
while True:
func()
try:
act_3 = int(input("Enter the number of henchmen you want to fight : "))
if act_3 == 8:
print("\n You easily fight the 8 henchmen and defeat them to proceed with the path!")
break
else:
print("Sorry you have been killed as the henchmen overwhelmed you as there were too many of them")
except:
print( "Sorry you have been kicked from the agency for quitting on the mission")
This will show your list of paths/questions until user enters correct option.

How to run python loop until correct input string is entered [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...

Name error in Python3 when name is defined [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I am in spyder trying to run a fairly simple python code (python 3.6.4), but when I run the code and use the input statements, it says the names are not defined, even though they should be.
#Module 4 project
#4/25/18
#Henry Degner
#This project is meant to determine whether or not certain people are qualified to go to an exclusive concert
#create function askAge, which will use an input statement and comparison operators to see if the user is old enough
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
#create function askHearing, yes or no question to do you have sensitive hearing
def askHearing():
hearing = str(input("Do you have sensitive hearing? "))
if( str(hearing) == "yes","y" ):
hearingReq = "do"
elif( str(hearing) == "no","n"):
hearingReq = "don't"
else:
print("Please type yes, or y, if you have sensitivehearing. If not, type no or n.")
hearing = str(input("Do you have sensitive hearing? "))
#create function askTicket, yes or no question to do you have a ticket
def askTicket():
ticket = str(input("Do you have a ticket for the concert? "))
if( str(ticket) == "yes","y" ):
ticketReq = "do"
elif( str(ticket) == "no","n"):
ticketReq = "don't"
else:
print("Please type yes if you have a ticket, or no if you don't.")
ticketReq = str(input("Do you have a ticket for the concert"))
#create function askFun, yes or no question to are you willing to have an awesome time
def askFun():
fun = str(input("Are you willing to have a great time?"))
if( str(fun) == "yes","y"):
funReq = "do"
elif( str(fun) == "no","n" ):
funReq = "don't"
else:
print("Please type 'yes' or 'no'")
fun = str(input("Are you willing to have a great time?"))
#use def main():
def main():
#print situation, will ask some questions to see if you can attend concert
print("Welcome to the Henry Degner Concert Venue! We have to ask you a few questions before we let you into the venue.")
#use askAge
askAge()
#use askHearing
askHearing()
#use askTicket
askTicket()
#use askFun
askFun()
#print user's answers
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
#use if-else statement, if all three conditions match requirements, print you can attend concert. If not, print you can't attend
#use main()
main()
the error outputs as
File "C:/Users/henry/Documents/Current Classes/Foundations of Programming/Module 4 project/Module 4 project script.py", line 60, in main
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
NameError: name 'age' is not defined
It also says that all of the other names in line 60 aren't defined. Thanks in advance!
You are getting NameError: name 'age' is not defined because variables from different functions are not shared until you declare them global or you return them from one method to another.
Read more about Python Scopes and Namespaces
Just return value from function to main method.
Returning value from method
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
return age
def main():
...
age = askAge()
.....
Same you need to do it for all methods,
askHearing()
askTicket()
askFun()

How to output the average when entering a number?

name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (prompt != 1234):
grades.append(grade1)
grade1 = input(prompt).strip()
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
I need this to print out the name and average. When I input '1234' it just goes on normally. Can you help me so it makes it output the else statement? Thanks.
This is one problem:
while (prompt != "1234"):
You're comparing the prompt (which is "Enter your grade...") to the number 1234, and the prompt never changes. Which means it will never be equal to 1234, so it will go on forever! I believe you want to compare to grade1, rather than prompt.
Another issue, is the else statement:
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
You don't need the else statement, because you want those statements to be executed after the while loops ends, right? Then just put them after the while loop. No need for an if or if-else statement!
With those corrections, the code will look similar to this:
name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (grade1 != "1234"):
grades.append(grade1)
grade1 = input(prompt).strip()
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
Only a few syntax errors were holding you back, so keep up the good work!

Categories