def LoginScreen():
global User_Points
User_Points = 5
print("Welcome to Area Trainer")
print("Please enter the username for your account")
global user_name
user_name = str(input())
save = open(user_name + '.txt', 'w')
points = open(user_name + 'Score' + '.txt', 'w+')
points.write(str(User_Points))
PasswordCheck= True
while PasswordCheck:
user_password = input("type in your password: ")
if len(user_password) < 8:
print("your password must be 8 characters long")
elif not any(i.isdigit() for i in user_password):
print("you need a number in your password")
elif not any(i.isupper() for i in user_password):
print("you need a capital letter in your password")
elif not any(i.islower() for i in user_password):
print("you need a lowercase letter in your password")
else:
PasswordCheck = False
def MenuTriangle():
global User_Points
print('''Here is a triangle with a height of 12cm and a width of 29cm
/\ | *Not to scale.
/ \ |
/ \ | 12cm
/ \ |
<------->
29cm
You must find out the area and select the correct answer from these options''')
print('''A) 175
B) 174
C) 2000
D) 199
''')
user_input = input().upper()
if user_input == "A":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "C":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "D":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "B":
print("Congratulations! You got it right, someone's a smart cookie. Here have two points!")
reading = open(user_name + 'Score' + '.txt')
score = reading.read()
score = int(score) + 2
print("Your score is", score)
points = open('ok' + 'Score' + '.txt', 'w+')
points.write(str(score))
MenuStart()
def MenuStart():
print("Welcome to the mathematical area game!")
print("In this game you will be required to calculate the area of multiple shapes.")
print("To do this you must know how to calculate the area of different shapes with increasing difficulty")
print('''Please select a shape you want to play,
A) Triangle
B) Square
C) Circle''')
user_input = input().upper()
if user_input == "A":
print("You have chosen to calculate the area of a triangle!")
MenuTriangle()
elif user_input == "B":
print("You have chosen to calculate the area of a square!")
MenuSquare()
elif user_input == "C":
print("You have chosen the calculate the area of a circle!")
MenuCircle()
else:
print("Oops! I didn't understand that >:")
MenuStart()
LoginScreen()
MenuStart()
Hello, I am trying to make a small game where the user has to guess what the area of the shape is and if they get it right then they get 2 points however, I am using an external file to store the score of the game in but every time I play through the game by entering my name, password I will see that the value of the score will be changed to 2 after I get the answer right but then when it calls the menu function the score in the file is reset and I don't know why
CORRECT ANSWER TO SAVE PRESSING BUTTONS IS B
THE ONLY OPTION AVAILABLE TO PLAY IS TRIANGLE FOR NOW. If anyone could please figure this out it would be greatly appreciated.
This is because Python automatically overrides data in a file every time it is being opened. You are opening the file multiple times by calling the function multiple times.
Related
I'm making a game with python and I want to make it so that, there are items added into the backpack. I chose to use append but I don't know why it isn't working. Here is the code:
while True:
direction = input("\nEnter your letter (R, L, F, P, B): ").upper()
if direction == "L":
print(images.number)
elif direction == "F":
password = input("\nEnter the 6-letter password: ").upper()
if password == "CHANGE":
score = score + 30
print(f"Congratulations on solving this puzzle. You have gained 30 points, nice to know you can listen to instructions. Slowly open up the box, to get the key and vial. Put the vial in your bag and head to the door to unlock it.")
else:
print("That is wrong, can you look at the instructions properly!")
print(direction)
elif direction == "P":
print(score)
elif direction == "B":
if score == 50:
backpack.append("Vial of Virus")
print(f"Your backpack contains:")
for y in backpack:
print(y)
else:
print(f"Your backpack contains:")
for x in backpack:
print(x)
elif direction == "R":
if score == 50:
print("You insert the key into the keyhole and turn it. The door creaks open, and you slowly enter into the last and final room.")
break
else:
print("Find the key to the door!")
print(direction)
here is the output I'm getting, there should be another item (Vial of Virus) instead of only those 2.
enter image description here
The append function works in this example you've given assuming that score is equal to 50 when the user inputs B. The only reason that the append function doesn't work is if the score is not equal to 50.
Enter your letter (R, L, F, P, B): B
Your backpack contains:
Vial of Virus
Enter your letter (R, L, F, P, B):
Code that made the above terminal output:
score = 50
backpack = []
while True:
direction = input("\nEnter your letter (R, L, F, P, B): ").upper()
if direction == "L":
print(images.number)
elif direction == "F":
password = input("\nEnter the 6-letter password: ").upper()
if password == "CHANGE":
score = score + 30
print(f"Congratulations on solving this puzzle. You have gained 30 points, nice to know you can listen to instructions. Slowly open up the box, to get the key and vial. Put the vial in your bag and head to the door to unlock it.")
else:
print("That is wrong, can you look at the instructions properly!")
print(direction)
elif direction == "P":
print(score)
elif direction == "B":
if score == 50:
backpack.append("Vial of Virus")
print(f"Your backpack contains:")
for y in backpack:
print(y)
else:
print(f"Your backpack contains:")
for x in backpack:
print(x)
elif direction == "R":
if score == 50:
print("You insert the key into the keyhole and turn it. The door creaks open, and you slowly enter into the last and final room.")
break
else:
print("Find the key to the door!")
print(direction)
to learn Python I'm working on a small terminal upgrade game. The user enters a number that is added to a random integer to get a score (called "Films Produced" in game). The problem I can't seem to fix is every time the player goes to the menu and back then back to entering more numbers the previous number is deleted instead of added on to the new one.
Here is the code:
print("TERMINAL FILM by Dominick")
print("---------------------")
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score = user_input
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game()
def game():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game()
else:
filmClicker()
game()
So I want the player to be able to insert a number, the number gets added to another number by the computer, and then a final number is spit out. I got all that working. But it doesn't save when you do that multiple times. Which I don't want, I want it to stack each time you do it.
Sorry if I poorly explained it, I can answer more about it if needed. Any help is appreciated.
UPDATE:
I removed the score = "input" variable and declared it out of any function. But it's still not saving. Here is a better answer as to what I want it to do:
In the picture below I start at the game menu. I then decide to make films, I do it 5 times. But then when I go back to the menu and check my balance, the balance equals the last time I made films and not the TOTAL films. What I want it to do is add up all of the films. So in this case 48 + 49 + 9 + 38 + 25 instead of having just the last set (which is 25 in this case), to get a total balance which can be displayed by going to the menu and typing "B."
Here is the current code:
import random
score = 0
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
SECOND UPDATE:
Updated Code:
import random
score = 0
# PRINT BLANK LINE
def press_enter():
press_enter = print(input(""))
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score += user_input
produced = random.randint(1, 50)
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score += produced
print("")
print(">> You produced:", produced, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
In the picture below it's printing how much the player is producing from that turn but I also am testing the score (which is what the 6 and 49 stand for). It's scaling weird like that, where it adds a certain amount after every turn. Any way to fix this?
I think you are looking for the += operator.
Keep the score = 0 at the top of the file to initialize the variable, then use score += user_input to keep a running tally. This is the same as writing score = score + user_input.
In your filmClicker function, you should remove the following line:
score = user_input
By assigning to it, you've essentially erased its previous value which is why it doesn't accumulate between rounds.
For saving data, You can Use Files in python
For Saving:
f=open("data_game.txt","w")
f.write(<your score>)
f.close()
For Reading:
f=open("data_game.txt","r")
score=f.read()
print(score)
f.close()
I'm working on a simple program that allows the user to bet some virtual currency on a coin toss. Everything works fine, except for when the user inputs something incorrectly. For example: if a question asks for y/n response and the user puts 'd' or something as the response, the program will use the except ValueError and rerun the function. However, when the function is rerun and the user finally inputs something correctly, it will result in a further error.
Error:
> AttributeError: 'NoneType' object has no attribute 'lower'
Code:
import time
import random
money = 5000
last_interest_time = time.time()
def interest():
global money, last_interest_time
if time.time() - last_interest_time > 5:
prev_money = money
money *= 0.1
last_interest_time = time.time()
print("You now have " + str(money) + " monies (+" + str(money - prev_money) + ") from interest")
def game():
global money, last_interest_time
print("You have " + str(money) + " monies.")
choice = get_choice("Want to bet on a coin toss?", 'y','n')
if choice.lower() == 'y':
print("That's great!")
choice = get_choice("What side do you want to bet on?", 'h', 't')
bet_amount = get_bet()
print('Flipping the coin...')
time.sleep(1)
side = random.choice(['h', 't'])
if side == 'h':
print("The coin landed heads!")
elif side == 't':
print('The coin landed tails!')
if side == choice:
print("You won and received " + str(bet_amount) + " monies!")
money += bet_amount
else:
print("You lost the bet and " + str(bet_amount) + " monies!")
money -= bet_amount
game()
elif choice.lower() == 'n':
input('Oh well. Just type something if you want to bet again. ')
game()
def get_choice(question, response_1, response_2):
choice = input(question+" ("+response_1+'/'+response_2+'): ')
if choice != response_1 and choice != response_2:
print('Input is invalid. Must be '+response_1+'/'+response_2)
get_choice(question, response_1, response_2)
else:
return choice
def get_bet():
bet_amount = input("What amount do you want to bet?: ")
try:
if int(bet_amount) > money:
print("You don't have enough money!")
get_bet()
else:
return int(bet_amount)
except ValueError:
print('Invalid input. Must be a number')
get_bet()
game()
Debugging tip:
Print choice every time so you can see why it's crashing! You can take the print statement out later.
What I found was this:
get_choice() returned None.
In get_choice, if the input is invalid, it doesn't actually return anything. Oh no! So you're returning None, and calling .lower() on None throws the exception.
Solution:
You are on the right track when you run get_choice a second time if the input is invalid. One small tweak: instead of just running get_choice, return get_choice.
There is a similar bug in get_bet(), just a heads up, and you can solve it the same way.
Overall, great game.
.lower() runs on strings only and defining a variable with input() makes it not register as a string. Instead try something like this.
def set_choice():
choice = input("Want to bet on a coin toss?", 'y','n')
def choice():
choice = set_choice()
return choice
choice = choice.lower()
I wrote a simple program for class; it gives the user the choice of 5 different questions to solve, area of a circle, volume of a cylinder/cube, or surface area of cylinder/cube. The user has to decide which problem they want to solve, and if they make an invalid decision the program loops back to the start to let them try again. However, I can't figure out how to break the loop; after solving one of the problems it still loops back to the start of the program.
invalid_input = True
def start () :
#Intro
print("Welcome! This program can solve 5 different problems for you.")
print()
print("1. Volume of a cylinder")
print("2. Surface Area of a cylinder")
print("3. Volume of a cube")
print("4. Surface Area of a cube")
print("5. Area of a circle")
print()
#Get choice from user
choice = input("Which problem do you want to solve?")
print()
if choice == "1":
#Intro:
print("The program will now calculate the volume of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate volume
if radius > 0 and height > 0:
import math
volume = math.pi * (radius**2) * height
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Inputs, please try again.")
print()
elif choice == "2":
#Intro:
print("The program will calculate the surface area of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate surface area
if radius > 0 and height > 0:
import math
pi = math.pi
surfaceArea = (2*pi*radius*height) + (2*pi*radius**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + " units." )
invalid_input = False
elif radius < 0 or height < 0:
print("Invalid Inputs, please try again.")
print()
elif choice == "3":
#Intro:
print("The program will calculate the volume of your cube.")
print()
#Get edge length
edge = float(input("What is the length of the edge?"))
print()
#Calculate volume
if edge > 0:
volume = edge**3
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "4":
#Intro:
print("The program will calculate the surface area of your cube.")
print()
#Get length of the edge
edge = float(input("What is the length of the edge?"))
print()
#Calculate surface area
if edge > 0:
surfaceArea = 6*(edge**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "5":
#Intro
print("The program will calculate the area of your circle")
print()
#Get radius
radius = float(input("What is your radius?"))
if radius > 0:
#Calculate Area
import math
area = math.pi*(radius**2)
roundedArea = round(area,2)
print("The area of your circle is " + str(roundedArea) + " units.")
invalid_input = False
else:
print("Invalid Radius, please try again")
print()
else:
print("Invalid Input, please try again.")
print()
while invalid_input :
start ()
The preferred way for this kind of code is to use a while Truestatement like so,
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
This is an example, that you can correctly change for your needs.Here is the link to documentation.
You can add an option to exit.
print('6. Exit')
...
if choice=='6':
break
Or you can break on any non-valid input.
else:
break
invalid_input = True is a global variable (outside any function).
Setting invalid_input = False in your function sets a local variable, unrelated to the global one. To change the global variable, you need the following (greatly simplified) code:
invalid_input = True
def start():
global invalid_input
invalid_input = False
while invalid_input:
start()
Global variables are best to be avoided, though. Better to write a function to ensure you have valid input:
def get_choice():
while True:
try:
choice = int(input('Which option (1-5)? '))
if 1 <= choice <= 5:
break
else:
print('Value must be 1-5.')
except ValueError:
print('Invalid input.')
return choice
Example:
>>> choice = get_choice()
Which option (1-5)? one
Invalid input.
Which option (1-5)? 1st
Invalid input.
Which option (1-5)? 0
Value must be 1-5.
Which option (1-5)? 6
Value must be 1-5.
Which option (1-5)? 3
>>> choice
3
import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.