I have been trying to set up a health system for my school project but the value keeps resetting regardless of the fact that monster_health is outside of the loop, my friends and I can't seem to fix this.
Code:
monster_health = 100
while monster_health > 0:
playeraction = input('Placeholder beast wants to fight you!!\n1) Basic Attack')
print(monster_health)
if playeraction == 1:
monster_health = monster_health-7
continue
if monster_health <= 0:
print('You killed the monster!! Gain nothing, this is a test you barbarian')
break
Output:
Placeholder beast wants to fight you!!
1) Basic Attack
100 #should print 97 but fails to
replace
if playeraction == 1:
with
if playeraction == "1":
or:
if int(playeraction) == 1:
Because your input is string format and not an integer and 1 != "1".
From your code, you are printing the monster health before updating it, so it will be "100" (the initial value) the first time.
while monster_health > 0:
playeraction = input('Placeholder beast wants to fight you!!\n1) Basic Attack')
print(monster_health) # at this time, it is still 100
I am doing a program in which the user inputs the wage, name and the number of working hours per month for a certain number of employees. This piece of code is supposed to recieve Nemp employees and then ask for Nemp names. The problem is, it always skips the first name, it displays 'Employee name:' twice and doesn't allow the user to insert the first one. I don't understand why this is happening, any help would be greatly appreciated!
program test;
uses crt;
var
i, Nemp : integer;
employee: array of string;
BEGIN
read(Nemp);
SetLength (employee, Nemp);
for i:=1 to Nemp do
Begin
writeln ('Employee name: ');
readln (employee[i]);
end;
END.
Dynamic arrays are zero based. You should loop from zero to Nemp-1. Or loop from zero to High(employee).
And as #Rudy and #trincot points out, to read the length of the employee array, use ReadLn(Nemp) to avoid unwanted input effects.
A tip:
Enable range and overflow check in the compiler when debugging. That would have detected the error at the high range.
I am in my first year of coding. I am writing a program for school that I currently am having some issues with. The assignment is to create a trivia game using files. My code won't continue after I ask the user for an input to determine how many points the question they are asked will be worth. The section of the code with the problem is posted directly below. My entire program is below that in case that help anyone needs to see the whole thing. Just for the record the entire program is not finished yet.
P.S I am new at this so if I missed something obvious I apologize.
while repeat3==True:
#identifying what point value the player wants
print "what point value do you want the question to have?"
print "your options are:200,400,600,800,1000"
desiredValue=input()
print 'testing'
if desiredValue==200:
questionValue=random.randint(1,5)
repeat3=False
elif desiredValue==400:
repeat3=False
questionValue=random.randint(5,9)
elif desiredValue==600:
repeat3=False
questionValue=random.randint(8,13)
elif desiredValue==800:
repeat3=False
questionValue=random.randint(13,17)
elif desiredValue==1000:
repeat3=False
questionValue=random.randint(17,20)
else:
print 'please entre one of the good values'
#asking the user the question
print "Here is the question:"
print temporaryQuestions[currentCategory][questionValue]
here is my entire program so far
#quiz Master Project
#imports
import random
import time
#variables defined
categorys=["history", "vintage tv", "harry potter", 'mythology']
questionFiles=['history questions.txt','vintage tv show
questions.txt','HarryPotterQuestions.txt','mythQuestions.txt']
answerFiles=['history answers.txt','vintageTVAnswers.txt','HarryPotterAnswers.txt','mythAnswers.txt']
chosenCategory=0
HistoryQuestionsList=[]
TVQuestionsList=[]
HarryPotterQuestionsList=[]
MythQuestionsList=[]
temporaryQuestions=[HistoryQuestionsList,TVQuestionsList,HarryPotterQuestionsList,MythQuestionsList]
repeat1=True
repeat2=True
repeat3=True
desiredValue=0
name=0
# functions
#_______________________________________________________________________________
#turning the questions into lists
#history questions
a= open ('history questions.txt','r')
reader1=a.readlines()
for line1 in reader1:
HistoryQuestionsList.append(line1)
#vinatage tv
b= open('vintage tv show questions.txt','r')
reader2=b.readlines()
for line2 in reader2:
TVQuestionsList.append(line2)
#Harry potter
c=open('HarryPotterQuestions.txt','r')
reader3=c.readlines()
for line3 in reader3:
HarryPotterQuestionsList.append(line3)
#Mythology
d=open('mythQuestions.txt','r')
reader4=d.readlines()
for line4 in reader4:
MythQuestionsList.append(line4)
#prompting
print "hello and welcome to (for copyright reasons) japordy!"
print
print "what is your name?"
name=raw_input()
print
print "you are going to be able to chose from a few types of questions to answer"
time.sleep(.2)
print
print "you will be asked 10 questions"
time.sleep(.2)
print
print "first you need to decide what catagory to get a question from then, select a question on the basis of points."
time.sleep(.2)
print
print "you may chose from a different catagory each time"
time.sleep(.2)
print
print "after you are asked a question that question will be deleted from the questions that you can possibly get"
time.sleep(.2)
print
print "the point system works like this, if you get a question right you will be given the total number of points that question was worth."
print "But if you get the question wrong you will be fined the number of points that the question was worth."
print "if you take to long to answer you will not get a chance to answer and you will not recieve or be fined points"
time.sleep(3)
print
print "the catagories that you can chose from are: history, vintage tv, harry potter, and mythology"
time.sleep(.2)
print
print "the point values are 200, 400, 600, 800, and 1000"
print
#selecting the questions that will be asked
print "please entre the catagory you want to choose"
chosenCategory=raw_input()
chosenCategory=chosenCategory.lower()#converting all the letters to lowercase
#seeing if the user entered a valid category and if so creating a file that can be used for each round.
while repeat1==True:
while repeat2==True:
for i in range(1,5):
if chosenCategory==categorys[i-1]:
currentCategory=i-1
repeat2=False
if repeat2!=False:
#selecting the questions that will be asked
print "the catagories that you can chose from are: history, vintage tv, harry potter, and mythology"
print
print "please entre the catagory you want to choose"
chosenCategory=raw_input()
chosenCategory=chosenCategory.lower()#converting all the letters to lowercase
while repeat3==True:
#identifying what point value the player wants
print "what point value do you want the question to have?"
print "your options are:200,400,600,800,1000"
desiredValue=input()
print 'testing'
if desiredValue==200:
questionValue=random.randint(1,5)
repeat3=False
elif desiredValue==400:
repeat3=False
questionValue=random.randint(5,9)
elif desiredValue==600:
repeat3=False
questionValue=random.randint(8,13)
elif desiredValue==800:
repeat3=False
questionValue=random.randint(13,17)
elif desiredValue==1000:
repeat3=False
questionValue=random.randint(17,20)
else:
print 'please entre one of the good values'
#asking the user the question
print "Here is the question:"
print temporaryQuestions[currentCategory][questionValue]
UserAnswer=raw_input
For Python2, input () may not work. Use raw_input () if this is the case. Secondly, input is a string but you are comparing it with an integer. (1 is 0+1 or 2-1 but "1" is a stick and "2" is load of pixels that look like a swan swimming to the left. You can either compare it to "200" or compare int(desired_value) with 200.
Also, you might want to look at switch(),case,default for this or, since the code is almost identical in each case, an associative array of min/max values:
randMinMax = {200: {1,5}, 400: {5,9} ...}
while True: #infinite loop - see 'break' below
desired_input = int(raw_input) #Might want to try/catch in case of bad input
if desired_input in randMinMax:
questionValue=random.randint(randMinMax [desired_input][0], randMinMax [desired_input][0])
break; # Break out of loop
else:
print 'please entre one of the good values'
However, there is an even quicker version in this case since there is a fixed relationship between the input value and the random limits so:
limit = (desired_input / 200) - 1 # 0 to 4 inclusive
if limit==int(limit) and limit < 5: # not, for example, 215
limit = (limit * 4) + 1 # 1, 5, 9, 13, 17
questionValue=random.randint(limit,math.min (limit+4, 20)) # Because the last limit is 20, not 21 - hence math.min
break; # Got a result, stop looping.
A little more than you asked but these principals should help you along as you learn to code. Good luck and enjoy!
I'm creating a method where the user puts in a "PIN" number to access different methods.. Yes it's an ATM..
I'm trying to figure out how to make it so that the user gets a specific amount of tries until the program exit's..
After a bunch of research I haven't very well found anything useful.. The only thing I've found is to use .to_s.split(//) in order to add the number of the try into an empty array. Which doesn't make sense to me because why would you make an integer into a string..?
So my question is, how do you make it so that users only have a certain amount of tries, 3, until they get kicked out of the program?
Main source:
#!/usr/bin/env ruby
################
#ATM Rewrite
#
#Creator Lost Bam Not completed yet.
#
#11/19/15
##################
require_relative 'checking.rb'
require_relative 'savings.rb'
require_relative 'exit.rb'
require_relative 'loan.rb'
require_relative 'transfer.rb'
require_relative 'redirect.rb'
class ATM
attr_accessor :name, :checking_account, :savings_account, :pin_number, :transfer, :loan
def initialize( name, checking_account, savings_account )
#name = name
#checking_account = checking_account
#savings_account = savings_account
#pin_number = pin_number
end
end
##############
def pin
x = []
puts "Enter PIN Number:"
input = gets.chomp.to_i
if input == 1234
menu
else
x += 1.to_s.split(//) #<= This is what I found to convert integer to Array
puts "Invalid PIN, try again:"
input = gets.chomp
if x == 3
bad_pin
end
end
end
############
def menu #add #{name} on line 41
puts <<-END.gsub(/^\s*>/, ' ')
>
>Welcome thank you for choosing Bank of Bam.
>You may choose from the list below of what you would like to do
>For checking inquiries press '1'
>For savings account information press '2'
>To transfer funds press '3'
>To either apply for a loan, or get information on a loan press '4'
>To exit the system press '5'
>
END
input = gets.chomp
case input.to_i
when 1
checking_information
when 2
savings_information
when 3
transfer_funds
when 4
loan_info
when 5
exit_screen
else
puts "Invalid option please try again"
menu
end
end
def bad_pin
abort('Invalid PIN exiting sytem..')
exit
end
pin
Tried something new:
def pin
x = 3
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
return pin
if x == 0
bad_pin
end
end
end
It doesn't increment the number down it just keeps saying 3 tries left:
Enter PIN(3 attempts left):
4567
Invalid PIN
Enter PIN(3 attempts left):
45345
Invalid PIN
Enter PIN(3 attempts left):
6456
Invalid PIN
Enter PIN(3 attempts left):
4564
Invalid PIN
Your problem is that every time you recall the method the value of x resets again. You need to have a loop inside the pin method that'll keep track of attempts.
def pin
x = 3
while (x > 0) do
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
puts "no tries left" if x == 0
break if x == 0
end
end
end
Stay in the method. Recalling the method starts you back at three attempts.
I am working on a homework assignment that a user will input a grade percentage and it will output a letter grade. My issue is that I would like to restrict the user to only the number keys and a decimal point. If the user inputs anything else they will be prompted with an error message and will have a chance to input again. Here is my code that will work without the decimal, but I need the int to be float. Please help! Any feedback will be greatly appreciated!!
def percentLoop()
while True:
a = input('Enter a percent: ')
try:
number = int(a)
if (0< number <= 100):
return number
else:
print ('Enter a percent between 0 and 100.')
except:
print ('Please enter a percent between 0 and 100.')
Thanks for looking at what I have.
I haven't done python for ages, but is it just a matter of changing number = int(a) to number= float(a) ?