This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm new to programming and trying to create a branching story program in python. as far as I can tell everything should be working, but for some reason it doesn't register the input response, just repeats the original. (it doesn't rewrite the variable 'listo' like it should). Instead of moving on to the next line in the story(=rewriting 'listo' to the appropriate list and operating on it), it goes back to the first line of the story with it's 3 options. here's the relevant code:
#different story lines with their respective options
s1= 'You awaken from a sudden noise in your tent. An axe is coming straight towards your head.'
s2= 'You be dead.'
s3= 'The creature wielding the axe is thrown off balance by the momentum of his swing'
s4='You manage to parry the weapon away from you, where it sinks through your bed. The creature wielding it falls on top of you, carried by it’s momentum. You grapple with it on the ground trying to gain an advantage.'
s5='You run out of your tent. The entire camp is in a state of chaos. People and more of the creatures are skirmishing all around and a large amount of the camp is on fire. All of the pack animals are running around like headless chickens.'
s6='You take advantage of the creature’s misstep, lift up your small desk and bring it down hard on the creature’s head. It crumples and drops to the ground.'
s7='As you try to gain purchase on it’s throat the creature grabs your hand in its mouth and bites down hard. You feel white hot pain in your arm and black out.'
s8='You push the creature off of you and roll away.'
s9='You grapple in the dirt for something useful and manage to grab a hard oblong object. You stab it into the creature’s face and hear it squeal in agony as you push it off of you and get up. '
s10 = 'goodbye'
#different choices
o1='Roll out of the way'
o2='Try to block it'
o3='Stare at it and hope it goes away.'
o4='Exit program'
o5='Restart story'
o6='Run away'
o7='attack'
o8='Try to strangle it'
o9='Try to get it off of you'
o10='Try to find a weapon'
oo=''
#setting defaults so it wont give me issues:
a2 = []
a3 = []
a4 = []
a5 = []
a6 = []
a00 =[]
#the master lists. [story line, choices[references]]
a1 = [s1,o1,o2,o3,a2,a3,a4]
a2.append([s3,o6,o7,oo,a5,a6])
a3.append([s4,o8,o9,o10,a00,a00,a00])
a4.append([s2,o4,o5,oo,a00,a1,a00])
a5.append([s5,o4,o5,oo,a00,a1,a00])
a6.append([s6,o4,o5,oo,a00,a1,a00])
a00.append([s10,oo,oo,oo,a00,a00,a00])
correct_answers = ['a','b','c']
l = 0
#the program:
listo = a1
print(listo[4])
while True:
l +=1
print('\nloop '+ str(l)+ '\n')
x = input('\n'+str(listo[0])+'\nwhat do you do?: \na.'+str(listo[1])+'\nb.'+str(listo[2])+'\nc.'+str(listo[3])+'\n\nyour choice:')
print(type(x))
if x not in correct_answers:
print('Wrong answer wiseguy, type a lowercase a,b or c.')
print(x)
exit()
if x == 'a':
print('\ngot this far yall')
listo = listo[4]
print('\nreassigned value')
print(listo)
elif x == 'b':
listo = listo[5]
elif x == 'c':
listo = listo[6]
any help would be much appreciated, thanks!
Edit: post has been altered, see comments.
You are facing this error because the input() function always returns a string value. However, you are checking x against integers. Try using this instead:
x = int(input(...))
Here, you convert the input given by the user into an integer.
You can also change your code to be shorter like so:
x = int(input(...))
listo = listo[4][x - 1]
Related
I have a problem regarding a competition question I'm attempting to do. Here is the question (its a bit long)
""""
Welcome aboard, Captain! Today you are in charge of the first ever doughnut-shaped spaceship, The
Circular. There are N cabins arranged in a circle on the spaceship. They are numbered from 1 to N in
a clockwise direction around the ship. The ith and the (i + 1)th cabins are connected. So too are cabin
1 and cabin N.
Currently the ith cabin has Ai crewmates, however the spaceship cannot depart unless there are exactly
Bi crewmates in this cabin.
To achieve this, you have the power to pay crewmates to change cabins. You can pay a crewmate $1 to
move to an adjacent cabin. A crewmate can be asked to move multiple times, provided that you pay
them $1 each time.
What is the fewest dollars you must pay before you can depart? It is always be possible to depart.
""""
https://orac2.info/problem/aio22spaceship/ (the link to the intereactive Qs)
I searched the web and i found no solutions to the Q. My code seems to be infinite looping i guess but im not sure as i cant see what cases the sit uses to determine if my code is right.
Heres my code
#!/usr/bin/env python
import sys
sys.setrecursionlimit(1000000000)
#
# Solution Template for Spaceship Shuffle
#
# Australian Informatics Olympiad 2022
#
# This file is provided to assist with reading and writing of the input
# files for the problem. You may modify this file however you wish, or
# you may choose not to use this file at all.
#
# N is the number of cabins.
N = None
# A contains the initial number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
A = []
# B contains the desired number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
B = []
answer = 0
# Open the input and output files.
input_file = open("spacein.txt", "r")
output_file = open("spaceout.txt", "w")
# Read the value of N.
N = int(input_file.readline().strip())
# Read the values of A and B.
input_line = input_file.readline().strip()
A = list(map(int, input_line.split()))
input_line = input_file.readline().strip()
B = list(map(int, input_line.split()))
AM = A
#AM is my modifying set
# TODO: This is where you should compute your solution. Store the fewest
# dollars you must pay before you can depart into the variable
while AM != B:
#Check if the set is correct
#notfound is a testing variable to see if my code was looping due to input error
notfound = True
for i in range(N):
#Check which places needs people to be moved
while AM[i]>B[i]:
notfound = False
#RV and LV check the "neediness" for each half's people requirements. I check how many people
#are needed on one side compared to the other and subtract the "overflow of people"
RV = 0
LV = 0
for j in range(int(N/2-0.5)):
#The range thing makes sure that if N is odd, im splitting the middle but if N is even, i leave out the end pod
RV += B[(i+j+1)%N]-AM[(i+j+1)%N]
LV += B[(i-j-1)%N]-AM[(i-j-1)%N]
answer +=1
if RV>LV:
AM[i]+=-1
AM[(i+1)%N]+=1
else:
AM[i]+=-1
AM[(i-1)%N]+=1
print(AM,B)
if notfound:
break
print(answer)
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
please help i really neeed to know the answer, driving me mad ngl
Welp, there aren't any resources online and I've tried everything. I think the problem might be that because of my solving method, passengers may be flicked between two pods indefinitely. Not sure since i could make a case that demoed this.
also my post probably is messy since this is my first time posting
Part 2 Specific Word Count:
Hi, I have 3 parts that I am doing to this program and so far I have the first one which is wordcount. Part 2 is the specific word count and while I am able to put it in one of the elif statements, the requirement is to define it. I want to know how to define a specific input such as "ship" from a text file into my "Specific Word Count" where it says "print(2)"
Part 3 Find the Message:
If you can also help with this part this would be nice too. I'm looking for a secret message in the text file that is between 2 # symbols and I want to print what is between those 2 # symbols. The condition is also having to define it. I have tried a few things but so far no luck as well. This is what I have so far that has a word and I have tested all the if, elif, and else statements.
#################################################
from http.client import LineTooLong
import string
def display_menu():
print( "############################" )
print( "# 1 Total Word Count #" )
print( "# 2 Specific Word Count #" )
print( "# 3 Find The Message #" )
print( "# 4 Exit #" )
print( "############################" )
option = input('Enter your selection > ')
return option
##################################################
x = display_menu()
count = 0
def get_word_count( handle_input ):
handle_input.seek(0)
lines = 0
count = 0
for line in handle_input:
words = len(line.split())
count= count + words
return(count)
def get_specific_count( handle_input):
handle_input.seek(0)
def find_message( handle_input ):
handle_input.seek(0)
return(0)
while x != '4':
if x == '1':
fhand = open('Moby Dick.txt')
y = get_word_count(fhand)
print("Total:"+ str(y))
elif x == '2':
print(2)
elif x == '3':
print(3)
else:
print('Error try again!')
x = display_menu()
This is a Sample of what the Text file looks like since I cant attach a file
CHAPTER 1
Loomings.
Call me Ishmael. Some years ago--never mind how long
precisely--having little or no money in my purse, and nothing
particular to interest me on shore, I thought I would sail about a
little and see the watery part of the world. It is a way I have of
driving off the spleen and regulating the circulation. Whenever I
find myself growing grim about the mouth; whenever it is a damp,
drizzly November in my soul; whenever I find myself involuntarily
pausing before coffin warehouses, and bringing up the rear of every
funeral I meet; and especially whenever my hypos get such an upper
hand of me, that it requires a strong moral principle to prevent me
from deliberately stepping into the street, and methodically knocking
people's hats off--then, I account it high time to get to sea as soon
as I can. This is my substitute for pistol and ball. With a
philosophical flourish Cato throws himself upon his sword; I quietly
take to the ship. There is nothing surprising in this. If they but
knew it, almost all men in their degree, some time or other, cherish
very nearly the same feelings towards the ocean with me.
I am creating a text based RPG where the player starts with 600 skill points to allocate between 6 skills.
So I start by assigning the value 600 to the skill_points variable.
skill_points = 600
then I assign a default value for each skills variable.
skill_1 = 0
skill_2 = 0
skill_3 = 0
Now I ask the player for input for the first skill.
skill1_input = int(input("Skill 1:"))
And I update the value of the variables.
skill_1 = skill_1 + skill1_input
skill_points = skill_points - skill1_input
Then I use a if statement to check if the number submitted is above the leftover skill points available, If not It prompts you to input the next skill.
if skill1_input > skill_points:
print("Not Valid")
else:
skill_2input = int(input("Skill 2:"))
Nested IF/ELSE statements repeat throughout all 6 skills until you allocate all your points. It is in a while loop so that if you don't use all of your skill points, it starts over at the first skill.
However, it is very finicky. At first I put 100 points into each skill and it worked fine. When I put 100 points into the first skill then 200 into the next skill, it prints not valid, even though there 500 points left and 200 is not is not more then 500.
There are multiple similar scenarios where the math should work properly yet the program still prints not valid
What is the current way to do this? Should I have not designed it using if statements?
This can be better done with a for loop instead of nested if statements, and I would use an array for the skills.
skill_points = 600
skills = []
skill_inputs = 0
for i in range(6):
skill_input = int(input("Skill %i: "%(i+1)))
if skill_inputs + skill_input > skill_points:
print("Not Valid")
break
else:
skills.append(skill_input)
skill_inputs += skill_input
I rewrote your code and its functional to what you asked, but as an advice, before writing code, make sure your program makes fully sense to what you want to build(even if you don't know the tools to build it yet. That is what makes you learn more!)
If your code repeats itself, theres probably a better way to write it. As you can see, that code basically repeats itself 6 times.
You could replace it with:
skill_points = 600
skill_base = []
skill = 0
for i in range(6):
if sum(skill_base) == skill_points:
print("Values stored successfully!")
break
if sum(skill_base) > skill_points:
print("Not valid")
break
skill = int(input(f'skill_ {str(i+1)}: '))
skill_base.append(skill)
if sum(skill_base) == skill_points:
print("Values stored successfully!")
The problem with my code is that when running it to see if the first word of the question is in the query list. It won't give anything back due to being a int. Can anyone point me towards right direction ?
import random
response = [ 'Yes, of course!',"Without a doubt,yes.",
'For sure!','Ask me later.',
'I am not sure.',
'I will tell you after my nap.',
'No Way!','I do not think so.',
'The answer is clearly NO.']
query = ['Will','Are','Is','Am','Do','Can','May']
# Global lists ^^^
def main(response,query,ran):
# The program that
print('Ask a question that can only be answered in yes or no.')
question = input()
if question(0) in query():
ran(response,query)
res = ran(response,query)
print(res)
again = input('Enter Y or y to play again. Enter N or n to exit.')
if again in ['y','Y']:
main(lists)
else:
print('This program will now close.')
def ran(response,query):
res = random.choice(response)
return res
main(response,query,ran)
The problem lies here question.index(0) in lists. You are comparing apples with pears. index will yield a number and you are comparing it with the actual definition of the lists function. You might want to rethink what you want to compare.
Secondly, you will have extra errors, you are using random.sample in a bad way, you should be doing random.sample(response, 1)[0], I'm presuming you want to pick a random response from that collection.
Thirdly, what is the lists() function supposed to do?
So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.