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!
Related
i think the problem is in loop i don't know the program is just stopped after the first round but it's only giving one result and the rest is jut
keep repeating the same print statement and it's not giving a new random celebrity plus the score is always 1 or 0 #i don't know where the bug is but the
a=random.choice(data)
b=random.choice(data)
value1=a["follower_count"]
value2=b["follower_count"]
nameA=a["name"]
nameB=b["name"]
descriptionA=a["description"]
descriptionB=b["description"]
countryA=a["country"]
countryB=b["country"]
score=0
def compare_1(a,b):
game_continue=True
while game_continue:
a=b
b=random.choice(data)
while a == b:
b=random.choice(data)
print(f"compare A: {nameA},a {descriptionA}, from {countryA}")
print(vs)
print(f"compare B: {nameB},a {descriptionB}, from {countryB}")
answer_comp()
#clear()
#print(logo)
else:
game_continue=False
print(f"soory you loose : {score}")
def answer_comp():
global score
answer=input("who has more followers A or B ").lower()
global value1
global value2
if answer=="a" and value1>value2:
score+=1
print(f"correct,move to the next one your score is:{score}")
return a
elif answer=="b" and value1<value2:
score+=1
print(f"correct,move to the next one your score is:{score}")
return b
elif answer=="a" and value1<value2:
print(f"faulse,you loose your score is :{score}")
elif answer=="b"and value1>value2:
print(f"faulse,you loose your score is :{score}")
compare_1(a,b)
I want a user to be able to search for a specific term and if it is in the database a message will be given saying that it is in the database.
This is the code that I have made so far and it runs without errors, but when I enter a search term it always says "We are sorry, but that does not seem to be in our system" and it always says this 3 times. I am using Pycharm as my IDE, but I don't think that this should make a difference.
I am semi new to Python so please be patient with me if I have missed something simple : )
import csv
uIn = input("Please enter a search term: ")
with open('database.csv', 'r') as uFile:
fileReader = csv.reader(uFile, delimiter=',')
for row in fileReader:
if uIn == row[1]: #True
print (uIn + "is in file")
else: #False
print("We are sorry, but that does not seem to be in our system")
----------------------------------------------------------Edit----------------------------------------------------------------
Thank you, #Rahul Bhatnagar, for your answer; it showed me that I needed to switch == with in.
This does answer part of the question, and I have figured out some of the other part, the else statement prints for every row that does not have the uIn inside of it. So say the uIn was on the third row the script would print the #False statement twice and the #True statement once. This is alrightish, but if the uIn is on say the 50th row or the 100th row then there would be 49 or 99 #false statements printed.
I would now say that about 50% of my problem is fixed, the part that is not fixed, is to only print 1 #true or 1 #false statement if it is in the file.
import csv
def search(uIn):
found = false;
with open('database.csv', 'r') as uFile:
fileReader = csv.reader(uFile, delimiter=',')
for row in fileReader:
if uIn in row: #True
found = true;
if(found):
print ("Found the string in file!")
else:
print("We are sorry, but that does not seem to be in our system")
uIn = raw_input("ST: ")
search(uIn)
Where my database.csv file is :
search,terms,go,into,this,file,in,this,format
You're trying to find uIn at position 1 of row in all cases, which is not going to be the situation.
My assignment is to take the user's input and change every 'c' and 's' to 's' and 'th'.
After that it asked me to store the original user's input so it would not get changed.
I can't figure it out in Ruby.
print "What can we do for you?"
user_input = gets.chomp
user_input.downcase!
if user_input.length == 0
puts "Well you will have to write something...!"
elsif user_input.include?("s") || user_input.include?("c")
puts "We got ourselves some 's's and some 'c's"
user_input.gsub!(/s/, "th")
user_input.gsub!(/c/, "s")
puts "The changed version: '#{user_input}!'"
else
print "Nope, no 's' or 'c' found"
end
Don’t use inplace version of gsub:
# user_input.gsub!(/s/, "th")
# user_input.gsub!(/c/, "s")
gsubbed = user_input.gsub(/s/, "th").gsub(/c/, "s")
puts "Changed version: '#{gsubbed}'"
puts "Original version: '#{user_input}'"
Note the lack of exclamation signs in functions names.
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) ?