print("Descriptive Analytics:\n\t*1. Summary\n\t*2. Time Series\n\t*3.
Trend Lines\n\t*4. Moving Averages\nPredictive Analytics:\n\t*5.Linear
Regression Model\n\t*6.Non Linear Regression Model")
while True:
try:
choice = (input("Step 2: Please choose an option:"))
except ValueError:
print("Sorry, you've entered an invalid input. Please try again!")
if choice in ("1","2","3","4","5","6"):
break
if choice == "1":
print("Descriptive Analytics: Summary")
elif choice == "2":
print("Descriptive Analytics: Time Series")
elif choice == "3":
print("Descriptive Analytics: Trend Lines")
elif choice == "4":
print("Descriptive Analytics: Moving Averages")
elif choice == "5":
print("Predictive Analytics: Linear Regression Model")
elif choice == "6":
print("Predictive Analytics: Non Linear Regression Model")
Can anyone spot the error in this code? So far, the loop works effectively but fails to print the line "Sorry, you've entered an invalid input. Please try again!
You need to use proper indentation level and make sure your code is executed in else block, not except block,
while True:
try:
choice = (input("Step 2: Please choose an option:"))
except ValueError:
print("Sorry, you've entered an invalid input. Please try again!")
else:
if choice == "1":
print("Descriptive Analytics: Summary")
elif choice == "2":
print("Descriptive Analytics: Time Series")
elif choice == "3":
print("Descriptive Analytics: Trend Lines")
elif choice == "4":
print("Descriptive Analytics: Moving Averages")
elif choice == "5":
print("Predictive Analytics: Linear Regression Model")
elif choice == "6":
print("Predictive Analytics: Non Linear Regression Model")
if choice in ("1", "2", "3", "4", "5", "6"):
break
Related
I'm racking my brain on this and I'm sure it's unnecessary. I've tried looking for the answer online but it's leading me nowhere.
I'm writing a simple menu script (probably not the nicest format). In prompt 2, 3, 4 I'm in need of an option to get back to the previous prompt. Based on what I've found I just keep looping myself into a bigger and bigger issue.
Here is what I have:
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_cluster = 'Outdoors'
elif user_input2 == "2":
user_selected_cluster = 'Gym'
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_cluster = 'AM'
elif user_input4 == "2":
user_selected_cluster = 'PM'
else:
print("Invalid option selected. Run script again.")
exit()
I've tried a variety of while loops and even turning these into functions, which to be honest, I don't have a complete grasp of.
Every solution has just ended up with me looping the prompt I'm on, looping the entire script, or ending the script after prompt_1
Honestly would prefer to learn it instead of someone doing it but I can't even find good videos that address the subject.
Python (like many other languages) does not have a go to option.
The "goto" statement, which allows for unconditional jumps in program flow, was considered to be a bad programming practice because it can lead to confusing and difficult-to-maintain code. Instead, Python uses structured control flow statements, such as if, for, and while loops, which encourage clear and organized code that is easy to understand and debug.
However, you can put the code into functions to achieve the same result, like this:
def main():
''' the main module '''
# have 3 attempts at each question, then move on.
for i in range(3):
x = action_01()
if x != 'invalid': break
for i in range(3):
x = action_02()
if x != 'invalid': break
for i in range(3):
x = action_03()
if x != 'invalid': break
for i in range(3):
x = action_04()
if x != 'invalid': break
def action_01():
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_02():
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_action = 'Outdoors'
elif user_input2 == "2":
user_selected_action = 'Gym'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_03():
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_04():
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_action = 'AM'
elif user_input4 == "2":
user_selected_action = 'PM'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
if __name__ == '__main__':
main()
Note, there are even more efficient ways, but this will be a good starting point for you.
File "E:\P-L\Atom\RPS.py\RPS.py", line 34
if user_choice == "r":
IndentationError: unexpected indent
i'm new to code and i'm making a project
someone said the you learn better by doing projects
so here i am
i'm getting this on Atom
i've tried the same code on repl.it and it works
import random
comp_wins = 0
player_wins = 0
def Choose_Option():
user_choice = input("Choose Rock, Paper or Scissors: ")
if user_choice in ["Rock", "rock", "r", "R"]:
user_choice = "r"
elif user_choice in ["Paper", "paper", "p", "P"]:
user_choice = "p"
elif user_choice in ["Scissors", "scissors", "s", "S"]:
user_choice = "s"
else:
print("I don't understand, try again.")
Choose_Option()
return user_choice
def Computer_Option():
comp_choice = random.randint(1, 3)
if comp_choice == 1:
comp_choice = "r"
elif comp_choice == 2:
comp_choice = "p"
else:
comp_choice = "s"
return comp_choice
while True:
print("")
user_choice = Choose_Option()
comp_choice = Computer_Option()
print("")
if user_choice == "r":
if comp_choice == "r":
print("You chose rock. The computer chose rock. You tied.")
elif comp_choice == "p":
print("You chose rock. The computer chose paper. You lose.")
comp_wins += 1
elif comp_choice == "s":
print("You chose rock. The computer chose scissors. You win.")
player_wins += 1
elif user_choice == "p":
if comp_choice == "r":
print("You chose paper. The computer chose rock. You win.")
player_wins += 1
elif comp_choice == "p":
print("You chose paper. The computer chose paper. You tied.")
elif comp_choice == "s":
print("You chose paper. The computer chose scissors. You lose.")
comp_wins += 1
elif user_choice == "s":
if comp_choice == "r":
print("You chose scissors. The computer chose rock. You lose.")
comp_wins += 1
elif comp_choice == "p":
print("You chose scissors. The computer chose paper. You win.")
player_wins += 1
elif comp_choice == "s":
print("You chose scissors. The computer chose scissors. You tied.")
print("")
print("Player wins: " + str(player_wins))
print("Computer wins: " + str(comp_wins))
print("")
user_choice = input("Do you want to play again? (y/n)")
if user_choice in ["Y", "y", "yes", "Yes"]:
pass
elif user_choice in ["N", "n", "no", "No"]:
break
else:
break
Pretty sure the problem is with atom but i don't know what it is would love any help.
I don't have a lot of experience with python but I think this can be much simpler. If anything available for the same result. Using a dictionary mapping to functions instead of all those elif maybe?
choice = input("Select an option: ")
if choice == "1":
try:
new_contact = create_contact()
except NotAPhoneNumberException:
print("The phone number entered is invalid, creation aborted!")
else:
contacts[new_contact['name']] = new_contact
save_contacts(contacts, filename)
elif choice == "2":
print_contact()
elif choice == "3":
search = input("Please enter name (case sensitive): ")
try:
print_contact(contacts[search])
except KeyError:
print("Contact not found")
elif choice == "0":
print("Ending Phone Book.\nHave a nice day!")
break
else:
print("Invalid Input! Try again.")
I am making a rock, paper, scissors game for a programming class. This is where I got and then PowerShell spits out that error. I don't understand what is wrong (I am a beginning Python programmer). My programming teacher is not much help and prefers the "Figure it out" approach to learning. I am genuinely stuck at this point. Any help is appreciated, thank you!
import random
def rps():
computer_choice = random.randint(1,3)
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
def computer_choice_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("It's a Tie!")
try_again()
if user_choice == "2":
print ("You Win! Paper covers Rock!")
try_again()
if user_choice == "3":
print ("I Win and You Lose! Rock crushes Scissors!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_rock()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("I Win and You Lose! Paper covers Rock!")
try_again()
if user_choice == "2":
print ("It's a Tie!")
try_again()
if user_choice == "3":
print ("You Win! Scissors cut Paper!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == ("1"):
print ("You Win! Rock crushes Scissors")
try_again()
if user_choice == "2":
print ("I Win! Scissors cut Paper!")
try_again()
if user_choice == "3":
print ("It's a Tie!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def try_again():
choice = input("Would you like to play again? Y/N: ")
if choice == "Y" or choice == "y" or choice == "Yes" or choice == "yes":
rps()
elif choice == "n" or choice == "N" or choice == "No" or choice == "no":
print ("Thanks for Playing!")
quit()
else:
print ("Please type Y or N")
try_again()
rps()
You have a typo in you code
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
Comuter
Your code can be simplified to an extreme degree. See the following example program. To replace either of the players with a NPC, set player_1 or player_2 with random.choice(priority). If you want to, you could even have the computer play against itself.
priority = dict(rock='scissors', paper='rock', scissors='paper')
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif priority[player_1] == player_2:
print('Player 1 wins.')
else:
print('Player 2 wins.')
You could also adjust your game so people can play RPSSL instead. The code is only slightly different but shows how to implement the slightly more complicated game. Computer play can be implemented in the same way as mentioned for the previous example.
priority = dict(scissors={'paper', 'lizard'},
paper={'rock', 'spock'},
rock={'lizard', 'scissors'},
lizard={'spock', 'paper'},
spock={'scissors', 'rock'})
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif player_2 in priority[player_1]:
print('Player 1 wins.')
else:
print('Player 2 wins.')
I keep getting this error message that says expected an indent block.
The shell highlights the bold spot as the error. Any suggestions on how I fix it?
I am just a beginner so any and all help would be appreciated! Thank you in advance!
from random import *
s = choice( [ 'rock', 'paper', 'scissors' ])
def rps( ):
""" runs a game of Rock Paper Scissors between the program and the user by returning the user's choice and the program's choice and signaling a winner
input: the user's choice which is one of three responses in the game Rock-Paper- Scissors - all are a string of letters
"""
print ('rps( )')
print ('Welcome to a game of Rock Paper Scissors!')
print ('I just made my choice.')
print ('I promise no cheating this time!')
r = input('Now you choose rock, paper, or scissors!')
print
if r == 'paper':
print ('You chose paper.')
if s == 'scissors':
print ('I chose scissors. Haha, I win fair and square!')
elif s == 'rock':
print ("I chose rock. Maybe I'll have better luck next time...")
elif s == 'paper':
print ('We need a rematch!')
elif r == 'scissors':
print ('You chose scissors.')
if s == 'rock':
print ('I chose rock. Haha, I win fair and square!')
elif s == 'paper':
print ("I chose paper. Maybe I'll have better luck next time...")
elif s == 'scissors':
print ('We need a rematch!')
elif r =='rock':
print ('You chose rock.')
if s == 'paper':
print ('I chose paper. Haha, I win fair and square!')
elif s == 'scissors':
print ("I chose scissors. Maybe I'll have better luck next time...")
elif s == 'rock':
print ('We need a rematch!'
else:
print ("Don't you know the rules? Choose rock, paper or scissors!")
I think I fixed it!
from random import *
s = choice( [ 'rock', 'paper', 'scissors' ])
def rps( ):
""" runs a game of Rock Paper Scissors between the program and the user by returning the user's choice and the program's choice and signaling a winner
Technically this function has no inputs and no return value; the function is an interaction between the user and the program
"""
print ('Welcome to a game of Rock Paper Scissors!')
print ('I just made my choice.')
print ('I promise no cheating this time!')
r = input('Now you choose rock, paper, or scissors!')
if r == 'paper':
print ('You chose paper.')
if s == 'scissors':
print ('I chose scissors. Haha, I win fair and square!')
elif s == 'rock':
print ("I chose rock. Maybe I'll have better luck next time...")
elif s == 'paper':
print ('We need a rematch!')
elif r == 'scissors':
print ('You chose scissors.')
if s == 'rock':
print ('I chose rock. Haha, I win fair and square!')
elif s == 'paper':
print ("I chose paper. Maybe I'll have better luck next time...")
elif s == 'scissors':
print ('We need a rematch!')
elif r =='rock':
print ('You chose rock.')
if s == 'paper':
print ('I chose paper. Haha, I win fair and square!')
elif s == 'scissors':
print ("I chose scissors. Maybe I'll have better luck next time...")
elif s == 'rock':
print ('We need a rematch!')
else:
print ("Don't you know the rules? Choose rock, paper or scissors!")
Ok... all of this is really confused.
First of all, there is nothing inside the function rps() except for a comment. This is how you define a function:
def hi_im_a_function():
hi im inside the function
hi, im not inside the function.
hi_im_a_function()
^calling the function
In fact, that whole function appears to be obsolete. I don't know what you were trying to accomplish with that print('rps()') thing, but it isn't doing anything. I suggest you drop it.
The error is coming from that random floating print on the line right before the error. The error is landing on the if r == paper line because that is where the compiler first feels the effects of the error you set in the line before it.
As before, I don't know what you were trying to do there, but that statement has no purpose there. Delete it.
Fix those errors, and it should work like a charm.