How to sucsessfully ask the user to choose between two options - python

New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.

inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.

Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")

Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])

Related

Unable to get desired outcome of a while True loop

Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...

am trying to make the while loop repeats again and again by the user after it finishes

I am new in python and I am trying to make a very basic and simple guessing game , I wanted the loop to be repeated again after it had finished.... when the user type yes in the command the loop should repeat again please help me .....in line (31):
import random
password =[1,2,3,4,5,6,7,8,9,10]
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
#body of the game
while guess != password and not(out_of_guess):
if guess_count < guess_limit:
guess = input(" enter a guess : ")
guess_count += 1
else:
out_of_guess=True
if out_of_guess:
you_lose=True
print("you LOSE :( ")
# PLAYING again
while True :
answer = input("do you want to play again ??\n yes or no ?? \n ")
yes_input= "yes"
no_input= "no"
if yes_input == answer:
random.shuffle(password)
#here i want to return from the beginning to start playing again
elif no_input == answer:
break
else:
print("********INVALID INPUT********")
You can wrap the whole program in one while True loop; then when you get to the play again section, you can just restart with continue:
import random
password = [1,2,3,4,5,6,7,8,9,10]
while True :
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
while guess != password and not(out_of_guess):
if guess_count < guess_limit:
guess = input(" enter a guess : ")
guess_count += 1
else:
out_of_guess=True
if out_of_guess:
you_lose=True
print("you LOSE :( ")
answer = input("do you want to play again ??\n yes or no ?? \n ")
yes_input= "yes"
no_input= "no"
if yes_input == answer:
random.shuffle(password)
continue
elif no_input == answer:
break
else:
print("********INVALID INPUT********")
But right now, it is impossible for the password to be guessed because the password is a list and input() is returning a str. You could make a str version of the password to check against, though:
import random
password = [1,2,3,4,5,6,7,8,9,10]
while True :
str_password = ''.join(str(i) for i in password)
#so correct input is "12345678910"
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
while guess != str_password and not(out_of_guess):
#and so on
Your code doesn't even work. You compare a string to a list. I think that you want to choose random element (number) from the list, and then check if the input is equal to that random.
I organized your code and make it look more clean.
import random
pass_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def game(guess: int) -> str:
guess_count = 0
while not guess_count <= 3:
if guess == random.choice(pass_list):
return 'You won!'
guess_count += 1
return 'You Lose'
while True:
guess = int(input('Enter a guess: '))
print(game(guess))
if input('Play again? ').lower() == 'yes':
game(guess)
else:
break
Instead of writing your code that way, you can use a function to organize your code and it will make it easier to understand.
import random
def password_guessing():
guess_count = 3
while True:
print("\nGuesses remaining: " + str(guess_count))
value = int(input("Enter a guess: "))
guess = random.choice(password)
if value == guess:
print("Correct guess!\n You won")
break
else:
guess_count -= 1
if guess_count >= 1:
pass
else:
print("You Lose :(\n")
ans = input("You want to play again?(y/n): ")
if ans == 'n':
break
# declaring it again since value in guess_count is 0 currently
guess_count = 3
password = [1,2,3,4,5,6,7,8,9,10]
print("Password Guessing game!")
answer = input("Enter 'yes' in order to play: ")
if answer == 'yes':
password_guessing()
print("*****GAME OVER*****")
else:
print("*****GAME OVER*****")

How to loop the error trap back to the original question

I have a menu option of 5 things. If the user enters a number not between 1 and 5 my program reasks for the number but even if the user puts in a number that works the program still ends.
print(" ")
print("pick a menu option between 1-5")
print(" ")
print(" ")
print("1 - Enter RLE")
print("2 - Display ASCII art")
print("3 - covert ASCII art option")
print("4 - convert RLE option")
print("5 - Quit")
print(" ")
print(" ")
print(" ")
user=0
user=int(input('select a number between 1 and 5'))
if user == 1:
print("hi")
elif user == 2:
user = input('select a file with an ASCII art image')
f = open(user, 'r')
if f.mode == 'r':
showart = f.read()
print(showart)
# asking user for file
#showing the file
#file name LogoArt.txt
elif user == 3:
print("hi")
elif user == 4:
print("hi")
elif user == 5:
print('goodbye')
import sys
sys.exit()
#exits the program
else:
user=int(input("select a number between 1 and 5"))
i expect the output of else to be able to reask the original question
def ask (user) :
if user == 1:
print("hi")
elif user == 2:
user = input('select a file with an ASCII art image ')
f = open(user, 'r')
if f.mode == 'r':
showart = f.read()
print(showart)
elif user == 3:
print("hi")
elif user == 4:
print("hi")
elif user == 5:
print('goodbye')
import sys
sys.exit()
while (True) :
print(" ")
print("pick a menu option between 1-5 ")
print(" ")
print(" ")
print("1 - Enter RLE ")
print("2 - Display ASCII art ")
print("3 - covert ASCII art option ")
print("4 - convert RLE option ")
print("5 - Quit ")
print(" ")
print(" ")
print(" ")
user=int(input("Select an integer between 1 and 5 : "))
if (user<5 and user > 1) :
ask(user)
else:
user=int(input("Please enter a number between 1 and 5 : "))
while (user > 5 or user < 1) :
user=int(input("Please enter a number between 1 and 5 : "))
ask (user)
Output:
Here's a nice, simple, and loop-free answer with function definition and even a little recursion in there for you. Really good things to learn if you're new to python or programming in general. Best of luck to you. And feel free to ask any questions about how it works.
def Menu():
#Put all your option prints here.
print(" ")
print(" ")
Option = int(input("Pick an option between 1 and 5. ")
print(" ")
if Option == 1:
pass #Replace each "pass" with what you want that Option to do.
Menu()
elif Option == 2:
pass
Menu()
elif Option == 3:
pass
Menu()
elif Option == 4:
pass
Menu()
elif Option == 5;
import sys
sys.exit()
else:
Menu()
Menu()

indentation errors in main function for connect four in python

A few minutes ago my program was fine until I tried adding in a way to make the user be asked to play again. When I put in the loop and indented everything, something got messed up really bad when I took out this part since it didn't work. Now I cant fix the indentation and nothing will work correctly. Can anyone see obvious problems?
def main():
lastRow = 0
won = 0
draw = False
player1turn = True
print("Welcome to Connect Four!")
rows = input("Please enter a number of rows: ")
check = True
while check == True:
try:
if int(rows) <= 4:
while int(rows) <= 4:
rows = input("Please enter a Valid choice: ")
else:
check = False
except ValueError:
rows = input("Please enter a Valid choice: ")
columns = input("Please enter a number of columns: ")
check2 = True
while check2 == True:
try:
if int(columns) <= 4:
while int(columns) <= 4:
columns = input("Please enter a Valid choice: ")
else:
check2 = False
except ValueError:
columns = input("Please enter a Valid choice: ")
myBoard = []
myBoardTemp = []
for i in range(int(columns)):
myBoardTemp.append(0)
for i in range(int(rows)):
myBoard.append([0] * int(columns))
printBoard(myBoard)
check3 = True
while won == 0 and draw == False:
move = input("Please enter a move: ")
while check3 == True:
try:
if int(move) < 0 or int(move) > len(myBoard[0]):
while int(move) < 0 or int(move) > len(myBoard[0]):
move = input("Please enter a valid choice: ")
else:
check3 = False
except ValueError:
move = input("Please enter a valid choice: ")
myBoard, player1turn, lastRow = move2(myBoard,int(move) - 1,player1turn)
printBoard(myBoard)
won = checkWin(myBoard,int(move) - 1, lastRow)
draw = isDraw(myBoard, won)
if won == 1:
print("Player 1 has won!")
elif won == -1:
print("Player 2 has won!")
elif draw == True:
print("It is a draw!")
The line after while check3 == True: is not indented correctly
The try after while check3 == True: isn't properly indented, although I can't tell if that is a transcription error or was in your original code.

I am coding a calculator and need help allowing user inputs to be floats

Okay, this is my code, it is in python 3.4.3 and I do not know how I would go about allowing user inputs to be floats. Any help would be greatly appreciated.
It is a calculator and works perfectly but it does not allow user inputs to be floats(have decimal places) and a lot of calculations take place with inputs of decimal numbers so it kinda needs it. Thanks if you take the time to read that!
import time
def cls(): print ("\n"*100)
def add():
cls()
print("you have selected addition")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("Enter a numberical interger")
b = input ("enter your second number: ")
if b.isdigit() == True:
b = int(b)
print ("\n")
print ("ANSWER:",a,"+",b,"=",a+b)
print ("\n")
def sub():
cls()
print("you have selected subtraction")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print ("ANSWER:",a,"-",b,"=",a-b)
print("\n")
def multi():
cls()
print ("you have selected multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"*",b,"=",a*b)
print("\n")
def divide():
cls()
print ("you have selected division")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
c = (a/b)
if a%b ==0 :
print("\n")
print ("ANSWER:",a,"/",b,"=",int(c))
print("\n")
else :
print("\n")
print ("ANSWER:",a,"/",b,"=",float(c))
print("\n")
def indice():
cls()
print ("you have selected indice multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
while (int(a)) >=1000000000000:
print("value too high, enter a lower value")
time.sleep(1)
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
while (int(b)) >=1000:
print("value too high, enter a lower value")
time.sleep(1)
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"To the power of",b,"=",a**b)
print("\n")
def Tconv():
cls()
print("You have selected unit conversion")
print("\n")
print("Enter 1 for conversion from celcius")
print("Enter 2 for conversion from kelvin")
print("\n")
a = input("Enter your choice: ")
if a == "1":
cls()
Tcelc()
elif a == "2":
cls()
Tkelv()
else:
print("Not a valid entry, try again")
time.sleep(1)
cls()
Tconv()
def Tcelc():
print("You have selected conversion from celcius")
print("\n")
a = input("Enter your celcius value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
cls()
Tcelc()
elif a.isdigit() == True:
print("\n")
print("AWNSER = ",(int(a))+273,"Kelvin")
print("\n")
def Tkelv():
print("You have selected conversion from kelvin")
print("\n")
a = input("Enter your kelvin value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
Tkelv()
elif a.isdigit() == True:
print("ANSWER = ",(int(a))-273,"Celcius")
print("\n")
def OpEx():
cls()
print("what operation would you like to preform?")
print("\n")
print("Enter 1 for addition")
print("Enter 2 for subtraction")
print("Enter 3 for multliplication")
print("Enter 4 for division")
print("Enter 5 for indice multiplication")
print("Enter 6 for unit conversion")
print("\n")
print("Or type 'close' to exit the program")
print("\n")
task = input("enter your choice: ")
print("\n")
if task == "1":
add()
menu()
elif task == "2":
sub()
menu()
elif task == "3":
multi()
menu()
elif task == "4":
divide()
menu()
elif task == "5":
indice()
menu()
elif task == "6":
Tconv()
menu()
elif task == "close":
exit()
else:
print ("not a valid entry")
time.sleep(2)
OpEx()
def menu():
Q1 = input("Type 'yes' to preform a calculation type 'no' to exit: ")
if Q1 == "yes":
OpEx()
if Q1 == "no":
print("sorry I could not be of futher service")
time.sleep(1)
exit()
else:
print("\n")
print("Not a valid entry, try again")
print("\n")
time.sleep(1)
cls()
menu()
cls()
menu()
You're converting user input to integers, which don't handle floating point all that well. Try converting to float instead, e.g.:
a = float(a)
I would be cautious taking the input as a float because python and many other languages floats are not represented as they may seem. I would recommend pulling the input as a string and then casting it later.

Categories