I want to loop the end section of the code if you get the 'Error, class not found'. I already tried a, for and while loop but i couldn't get it working.
Health = 0
Damage = 0
Classes = ['Mage','Knight']
Class = ''
print('Select Character Name.')
Name = input()
print('Hello',Name,'please choose your class.')
print('')
print('Mage: 5 Health: 7 Damage')
print('Knight: 7 Health : 5 Damage')
#looped section
Select = input()
if Select in ['Mage']:
print('Mage Selected')
Health = 5
Damage = 7
Class = 'Mage'
elif Select in ['Knight']:
print('Knight Selected')
Health = 7
Damage = 5
Class = 'Knight'
else:
print('Error, class not found')
#loop back if this is outcome
when facing problems like this, your default approach should be a while loop making sure that the loop will go on (virtually forever) if the defined conditions aren't met. so this is what you can do:
while True:
# looped section
Select = input()
if Select in ['Mage']:
print('Mage Selected')
Health = 5
Damage = 7
Class = 'Mage'
break # break the loop if selection is correct
elif Select in ['Knight']:
print('Knight Selected')
Health = 7
Damage = 5
Class = 'Knight'
break # break the loop if selection is correct
else:
print('Error, class not found, try again: ') # will start the loop over
Related
Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.
i am creating a telegram bot using python and i can't update the global variable in the callback function please help
i have tried to updated the variable using global FLAG inside a callback function but the variable is still the same
FLAG = 0
def start_all(bot,update):
global FLAG
chat_id = update.message.chat_id
FLAG = 0
sell = telegram.KeyboardButton(text="buy")
buy = telegram.KeyboardButton(text="sell")
custom_keyboard =[[ sell, buy ]]
reply_markup = telegram.ReplyKeyboardMarkup(
custom_keyboard)
bot.send_message(chat_id=chat_id,
text="Thank you",
reply_markup=reply_markup
)
command= update.effective_message.text
if command == "buy":
buy = Buy()
FLAG = 1
buy.start(bot,update)
elif command == "sell":
sell = Sell()
FLAG = 2
sell.start(bot,update)
else:
#help
pass
def main():
updater = Updater('')
dp = updater.dispatcher
dp.add_handler(CommandHandler('test',test))
dp.add_handler(CommandHandler('start',start_all))
if FLAG == 1:
buy = Buy()
dp.add_handler(MessageHandler(Filters.location,
buy.start))
elif FLAG == 2:
sell = Sell()
dp.add_handler(MessageHandler(Filters.location, sell.insert_user_to_database))
elif FLAG == 0:
dp.add_handler(MessageHandler(Filters.text, start_all))
else:
pass
i expected the FLAG will be 1 when i click buy ,2 when i click sell and check if i clicked buy or sell in main function and handle the filters accordingly
I am pretty sure that the IF statement is incorrect here. Telegram update.message.text is not a string so the evaluation will always fail and go to pass.
Try changing it to:
command = str(update.message.text)
Edit:
Additionally it seems to me you should be using a query-structure like this:
def start(update, context):
keyboard = [[InlineKeyboardButton("BUY", callback_data='buy'),
InlineKeyboardButton("SELL", callback_data='sell')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('WANT TO BUY OR SELL?', reply_markup=reply_markup)
updater.dispatcher.add_handler(CommandHandler('start', start))
def flag(update, context):
query = update.callback_query
command = str(update.callback_query.data)
if command == 'buy':
FLAG = 1
#do stuff
elif command == 'sell':
FLAG = 2
#do stuff
else:
pass
updater.dispatcher.add_handler(CallbackQueryHandler(flag))
I'm trying to make a program that will print an artist and the first letter of their song and the user has to guess the song. I can print the artist and then the first letter of the song but it also prints a random letter and then the first letter again after i type the correct song in. Why is this?
artist = ["NF","Jetta","Sickick","Kodaline","Eminem"]
# 0 1 2 3 4
song = ["Destiny","ZOO","Intro","Brother","Venom"]
# 0 1 2 3 4
import random
for x in range(0, 1):
random_number = random.randint(0,4)
first_let = []
for x in range(0,len(song)):
artist = artist[random_number]
print (artist)
letter = song[random_number][0]
print(letter)
guess = input()
if guess == song:
print("Well Done!")
attempts_left = 2
if attempts_left == 1:
print("You have one attempt left!")
exit
else:
attempts_left == 0
print("Unlucky, maybe next time.")
exit
I want it to say whether the guess is wrong or right but i just receive an error.
You can try the following code, it would work and it is simple to understand.
artist = ["NF","Jetta","Sickick","Kodaline","Eminem"]
# 0 1 2 3 4
song = ["Destiny","ZOO","Intro","Brother","Venom"]
# 0 1 2 3 4
import random
attempt = 2
r_num = random.randint(0,4)
for i in range(2):
artist_name = artist[r_num]
song_name = song[r_num]
print('Artist: ',artist_name)
print('Song first letter: ',song_name[0])
guess = input('guess the song: ')
if guess.lower() == song_name.lower():
print('Well done!')
break
else:
attempt -= 1
print('You have 1 attempt left')
if attempt == 0:
print('0 attempts, sorry')
break
Hope it helps in your case.
I'm not exactly sure why your code prints the extra letter, but I see a few problems, the most notable being that the "attempts" will never actually count down, since your code gets stuck in the for loop.
The following code should fix all your problems, and make your code both easier to read and modify (if you want change anything later):
import random
groups = [ # sorting artists like this simplifies the rest of the code
("NF","Destiny"),
("Jetta", "ZOO"),
("Sickick", "Intro"),
("Kodaline","Brother"),
("Eminem","Venom")
]
random.shuffle(groups)
attempts = 3
for group in groups:
artist = group[0]
letter = group[1][0]
song = group[1]
print(letter)
guess = input(f"Guess the name of {artist}'s song >>")
if guess == song:
print("Correct!")
continue
elif attempts == 0:
print("game over!")
break
else:
attempts -= 1
print(f"You have {attempts} attempts left!")
So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()
I'm trying to print a variable in Python using the following code:
from time import sleep
import random
class Hero:
def __init__(self,name):
self.name = name
if name == "rock":
self.health = 50
self.attack = 10
elif name == "paper":
self.health = 70
self.attack = 7
elif name == "scissors":
self.health = 100
self.attack = 5
def dmg(self, other):
other.ehealth -= self.attack
start = 1
while start == 1:
name = input("Pick a class [rock/paper/scissors]")
if name != "rock" or "paper" or "scissors":
print ("That player does not exist. Try again.")
start = 1
else:
start = 1
player = Hero(name)
enemyName = ["erock", "epaper", "escissors"]
ename = random.choice(enemyName)
print ("Your character is", name, "which comes with", self.health, "health, and", self.attack, "attack.")
print("")
sleep(1)
print ("Your enemy is", ename, "which comes with", ehealth, "health, and", eattack, "attack.")
I can't figure out a way to access and print the variable "self.health" under the "Hero" class. I can access "name" just fine. Maybe it's the fact that it's under an if statement? Can someone help me out?
self is just a parameter name used inside the methods. Don't use it outside the method.
To access the variables refer to them using the object name (player) like this
player.health
The name variable you are printing "works" because it's not from the object. You should use the same notation to access that too:
player.name