This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
scenario2(outcome) function calls sget_choice3 one so it either prints an outcome based on the users choice.
I want function to loop and ask for input twice if the Users selection is 0 (correct one is 1 and 0 is just a branch of it).
s2option_list3 =['Try to force it', 'Examine the door']
def sget_choice3(s2option_list3):
i = -1
while i <= 0:
print s2option_list3
choice3 = raw_input("> ")
for i, opt in enumerate(s2option_list3):
if opt in choice3:
i = i + 1
return i
else:
i = i + 2
return i
print "You need to select one of the given actions"
def scenario2_exit(outcome):
print outcome
choice = outcomes[0]
if outcome in choice:
print "conversation"
res3 = sget_choice3(s2option_list3)
if res3 == 0:
print "You try to force it but without any luck. However you do notice a little button on the left corner. "
else:
print "A small panel comes out, seems to be requesting a code. "
print "conversation"
else:
print "conversation"
Your issue appears to be in this line:
for i, opt in enumerate(s2option_list3):
When you use enumerate like that, it is overwriting your value for i (-1 at the time) with the index of the enumeration (0 for the first option and 1 for the second). I'm not sure why you are trying to use the enumeration at all.
Without giving you too much advice on how to restructure your program, a simple fix could be something like:
for opt in s2option_list3:
Related
I'm trying to create a "football" game on python and if the user wants to pass the ball, my code is supposed to have a 50% probability of having an incomplete pass or a completion yielding between 3 and 15 yards
I know that to print the yardage, the code would look something like
import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))
but I'm not sure how to make "Incomplete" show up as a 50% probabilty
You can use the code below. As you have defined a statement to pick a random number between 3-15, you can create another statement to pick 0 or 1 (not %50 guaranteed). Also in your code, you are assigning return value of the print function to a parameter. This is definitely wrong! Print function returns nothing so assigning it to another variable is meaningless.
x = random.randint(0,1)
if x == 1:
random.randint(3,15)
else:
# incomplete pass
You could use something like this.
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
print("ran successfully")
This: random.choice([random.randint(3,15),0]) is the important bit. random.choice takes multiple values (in this case 2) in a list, and picks one randomly (2 values => 50% probability).
I also fixed the input output thing. To get input from the user you assign the value of input to a variable like this: example = input("Your input here: "). If you ran that line of code, and answered with potato for instance, you'd be able to print example and get potato (or whatever the user answered) back.
If you'd like to really flesh your game out, I'd suggest looking into template strings. Those let you do wonderful things like this:
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
print("Ran successfully.")
This question already has answers here:
How to loop back to the beginning of the code on Python 3.7
(3 answers)
Closed 3 years ago.
I am using python 3, and I want to know how to return the code to the second linex = input ('Enter your first name here: ') after completing the if or elif conditions
I have searched other stack overflow answers but to no avail
print ("hello world")
x = input ('Enter your first name here: ')
if len(x) > 10:
print ("You have a long name")
elif:
print ("You have a short name")
Replace elif with else
The elif is short for else if. It allows us to check for multiple expressions. You aren't checking anything hence it should be replaced with else
Plus by doing that you fix a syntax error
elif:
^
SyntaxError: invalid syntax
This is not a valid Python statement.
edit:
if you want to repeat the question askeed to the user use a while loop:
in your case:
while True:
x = input ('Enter your first name here: ')
if len(x) > 10:
print ("You have a long name")
else:
print ("You have a short name")
This will work forever unless you kill it via a Task Manager or interrupt it using the keyboard.
You can use loop statement to return the second check condition again. Please refer this link for loops in python
for example of using while loop
answer = None
while True:
answer = raw_input("Do you like pie?")
if answer in ("yes", "no"): break
print "That is not a yes or a no"
it works like goto statement. you can use break or continue statement to stop or continue execution of loop.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm a beginner in coding and started because it's part of my course. I tried to make a function called displayOptions responsible for displaying options to the user and asking them for input from 1 to 7. Input such as string or numbers above 7 or below 1 should be rejected and the error message should be displayed.
def displayOptions():
#This part of the function is supposed to just print, and it's working correctly.
print ("Please select one of the following options:"), print ("1. Teaspoon to metric"), print ("2. Tablespoon to metric"), print ("3. Fluid ounces to metric"), print ("4. Pint to metric"), print ("5. Display list"), print ("6. Help"), print ("7. Close")
#Here I tried to make a loop until the user picks a number from 1 to 7 however the loop doesn't stop when the numbers are entered.
while True:
int(input) == (1, 7)
break
print("this is not a valid input, try to use a number from 1 to 7")
pass
pass
It seems like there are a few mistakes in your code. First of all, make sure your indentation is correct. See commented code for more explanation.
def displayOptions():
# there is an easier way to print your whole list: the escape char \n starts a new line.
print("Please select one of the following options:\n1. Teaspoon to metric\n2. Tablespoon to metric\n3. Fluid ounces to metric\n4. Pint to metric\n5. Display list\n6. Help\n7. Close")
while True:
# you are asking the user for input.
inp = input('') # Optionally, you're instructions could also be inside the input() function.
if int(inp) < 1 or int(inp) > 7: # you have to check whether the input is between 1 and 7 with an if condition
print("this is not a valid input, try to use a number from 1 to 7")
else: break # I don't know why you used pass all the time. But a break here in the else statement does the job as it exits the loop when the input is between 1 and 7.
displayOptions()
int(input) == (1, 7)
The expression you want here is
1 <= int(input) <= 7
and it should be part of an if statement.
(There are some other issues, but they're mostly indentation related so it's not possible to tell if they're in the code or just this post.)
As you probaby know, Python is strict to indentation, so the issue with your code could be that. Anyway there is a cleaner way to do it:
def displayOptions():
print ("Please select one of the following options:"), print ("1. Teaspoon to metric"), print ("2. Tablespoon to metric"), print ("3. Fluid ounces to metric"), print ("4. Pint to metric"), print ("5. Display list"), print ("6. Help"), print ("7. Close")
while True:
if 1 <= int(input()) <=7:
break
else:
print("this is not a valid input, try to use a number from 1 to 7")
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.
So here's what I'm trying to do:
The inputs will be in the correct syntax for Python. For example for this part:
conditionOne = input()
what the input will be something like "and 5 % 2 == 0"
So basically if conditionOne contains "and 5 % 2 == 0" and I have a statement which reads:
if exampleVariable == 1:
I need the program to get the string in the variable and put it into the if statement so it becomes
if exampleVariable == 1 and 5 % 2 ==0:
Is there any way to do this?
If I understand you correctly you can do something like this:
# Initializing
conditionTotal = 'exampleVariable == 1'
conditionOne = input()
# Updating
conditionTotal = conditionTotal + ' ' + conditionOne
# If you want to execute it
exampleVariable = 1
if eval(conditionTotal):
do_your_stuff()
But I wouldn't recommend you to code this way because you allow a user to enter any Python commands through the standard input that is completely unsafe because the user may execute an arbitrary Python program though yours.