Creating a continues loop with try | Python3 - python-3.x

I'm trying to receive user input that has to be between 2 and 10 and then return a message if the input is in fact between 2 and 10.
What I'm struggling with:
if the user inputs something other than a number, I get a ValueError
How I'm trying to resolve it:
I use the try except finally method.
Issue I'm unable to resolve:
When the user inputs a letter, the first time around, it will bring up the try: but if the user then inputs a letter a second time, it will give an error once again.
How can I make this loop so the user can give as many wrong answers as he wants and get it to it's final destination once he inputs a value between 2 and 10?
My code so far
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
except ValueError:
print(f"That wasn\'t a number! Try again.")
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
finally:
print("Good, welcome to the dark side.")
Would appreciate the help!
Thanks.

This example works, while making minimal changes to your code:
while True:
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
break
except ValueError:
print(f"That wasn\'t a number! Try again.")
print("Good, welcome to the dark side.")
The main differences are removing the while loop from within the except and the finally portion, and using a while True loop to continue asking the question until the conditions are met that lead to the break (i.e. user enters a value between 2 and 10, inclusive). My test of this code works.

Related

Is there a way to return to input if condition is not met in python?

What i am trying to do do is this.
1.User Inputs a number (for example a SSN or any Identification number)
2.If the user is not 14 digits, return to the input and try again
3.If Input is 14 digits, continue in program.
4.Check if SSN starts with 1 or 2 (in my scenario all male ID start with 1 and all female ID start with 2
5. If 1 print male if 2 print female.
My last code is:
ssn=str(input("SSN: "))
x=len(ssn)
while x != 14:
print("Wrong digits")
break
else:
print("Thank you")
y=str(ssn[0])
if y == 1:
print("Male")
else:
print("ok")*
In execution i get:
SSN: 12345
Wrong digits
ok
The problem is that this does not break if i input 12 digits. It does say wrong digits but continues to in the execution.
Second problem is that it prints ok even though i added 1234 which starts with 1 and it should be male.
Any ideas on this please?
First str(input(...)) is unnecessary, as input already returns a string (why convert string to a string ?). Second, you update neither ssn nor x. Third, while x != 14 will run only as long as x is unequal 14. But you want it to do some processing when x is equal 14. Fourth, 1 == "1" will always be False. Following code should work:
while True: # endless loop
ssn = input("SSN : ")
if not ssn.isdigit(): # if the ssn is not a number, stop
print("not a number")
continue # let the user try again
l = len(ssn)
if len(ssn) != 14:
print("Wrong digits")
continue # let the user try again
else:
print("Thank you")
if ssn[0] == "1":
print("Male")
else: # This will print Female even if first ID digit is 3 or 4 or whatever, should use elif ssn[0] == "2"
print("Female")
break # stop asking again
another shorter and cleaner way to do this is by using regular expressions:
import re
while True:
SSN = input('Enter number:')
if re.match('1\d{13}',SSN): # 1 + 13 digits
print('Male')
break
elif re.match('2\d{13}',SSN):# 2 + 13 digits
print('Female')
break
elif re.match('\d{14}',SSN): # 14 digits
print('Thank you')
break
print('Try again')

How can I not allow letters, and only allow numbers in an input on python 3?

I am a beginner. I'm making a survey, and one of the questions asks the users age. How can I make it so that if the user enters a letter or symbol, it shows a print() message?
The issue seems to be that the computer reads the first if statement of "if age < 10:" and then sends an error message in the terminal if I enter a string.
This is the code right now, I want it so that if the user inputs a letter(s) or symbol(s), it sends a print() message, and asks for the input again, is that possible?
c = 3
while c == 3:
age = int(input('How old are you (enter a number)? '))
if age < 10:
print("Wow, you're quite young!")
break
elif age > 60 and age <= 122:
print("Wow, you're quite old!")
break
elif age > 122:
print('Amazing! You are the oldest person in history! Congrats!')
break
elif age >= 14 and age <= 18:
print('Really? You look like a college student!')
break
elif age >= 10 and age <= 13:
print('Really? You look like a 10th grader!')
break
elif age > 18 and age <= 60:
print('Really? No way! You look younger than that, could have fooled me!')
break
Define each operation in your survey as a different function. Then you can use a statement like this one:
try:
int(input_variable)
except ValueError:
function()
To check if they gave you an integer, and if they didn't they have to input again. You seem to be a beginner so I can answer questions if you have any.
for simple solution, simply loop until integers are received.
while True:
try:
age = int(input('How old are you (enter a number)? '))
except ValueError:
print('input should be integer!')
continue
break

Python 3.7 guess the number program not looping back to options input when option one is finished

When option one finishes and you have guessed the right number, the program is breaking out of all loops, printing exit program and exiting. I need it to loop back to the options input, option=int(input("Choose an option 1 -3 ")). Option 2 loops back to options input fine. I can't see anything different in the code to tell me why this is happening.
I have been online with 2 tutors who did nothing but break my code into uselessness. I am new to coding so my code may be sloppy or not what people are used to seeing.
I get no error messages, the code works except for option 1 not looping back to options input. When option 1 finishes it ends the program instead of looping back to option=int(input("Choose an option 1 - 3 "))
#display welcome message
print("Welcome to the guess my number program")
import random
#start outside while loop for options
while True:
print("1 You guess the number ")
print("2 You enter a number and see if the computer can guess it ")
print("3 Exit Program ")
#get option input from user
#inside if loop and set random integer
option = int(input("Choose an option 1 - 3 "))
#option 1
if(option == 1):
myNumber = random.randint(1, 10)
#set count
count = 1
#inside while loop
while True:
try:
print("Guess a number between 1 and 10 ")
#get guess
guess=int(input("Guess a number"))
#inside while loop
while guess<1 or guess>10:
print("Invalid entry, please choose a number between 1 and 10 ")
#get guess
guess=int(input("guess a number "))
except:
print("Please enter numbers only ")
continue
#display guess result to user, tally guess count
if guess < myNumber:
print("Your guess is to low, guess again")
count = count + 1
elif guess > myNumber:
print("Your guess is to high, guess again")
count = count + 1
elif guess == myNumber:
print("Great job, you guessed it in "
+ str(count) + " attempts \n")
break
#option 2
if (option == 2):
count = 1
#get number input from user
number = int(input("Choose a number for the computer to try to guess "))
while True:
#get random value from computer
computerGuess = random.randint(1, 10)
#inside if loop, display guess to user, tally guess count
if(computerGuess < number):
print("Computer guess is to low")
count = count + 1
elif(computerGuess > number ):
print("Computer guess is to high")
count = count + 1
elif(computerGuess == number):
print("The computer has guessed the right number in "
+ str(count) + " attempts. The number was " + str(number) )
break
else:
print("You are exiting the program")
break
If your intention is to stay in the program unless someone types a different number than 1 or 2 as option, then
Your indentation of 'if' statement for option 2 should be at similar level as option 1.
Option2 clause should be an 'elif', rather than a separate 'if' condition.
Last 'else' block (which exits the outer loop) should also be within the outer While Loop

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Python 3.5.1 Introduction to Python 2.1 Mark Clarkson - While Loop Issue

I'm working my way through this set of tutorials. In section 3.2a - While Loops the following code is supposed to loop until the user enters the target number (7) then display a congratulations message however regardless of what number is entered Python either gives a right answer or a wrong answer, even 7 will sometimes flag a wrong answer. I know there are other ways to perform this sort of task but I would like to get the code from the tutorial working.
targetNumber = 7
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
You should convert the target numger to an string before comparison. Also, you should exclude the congratulations message from the loop. I would suggest :
targetNumber = str(7)
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
print("Wrong, try again ")
guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")
The detail is that input returns a string and if you compare a string to an integer, it will always return false.
Python's input function (or raw_input in Python 2.x) returns a string entered by the user. targetNumber, on the other hand, is an integer. In the Python Interpreter, try:
>>> 7 == "7"
False
You need to cast the user's input to an integer first.
try:
guess = int(input("Please enter a number: "))
except ValueError:
print("That is not a valid number!")

Resources