python while loop with break statement - python

Can please somebody tell me,
what the reason the break statement in this context is.
What would be the difference if i remove the breake statement from the code
i am new in python, many thanks in advance!
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."

The idea behind this is that it retrieves a string from the user with raw_input, and then tries to convert it to an integer. If the conversion is successful, it breaks out of the loop. If the conversion fails, it throws an exception, jumps over the break statement into the except block, and then goes back to the top of the loop to ask for the number again.

Related

Loop function yet break if certain code put into raw_input

I've been looking up on here and Google yet can't find the solution for what I'm looking for. "While" function keeps failing me as I don't know here I need to put it. I'm a total newbie so if you could kindly explain the solution, thank you:
number = raw_input("Number: ")
if int(number) % 2 == 0:
print "Even number"
else:
print "Odd number"
All I would like to do is to keep the function looping allowing the user to enter as many numbers as possible. It should only break if user puts in "stop" as the value.
Well if user types stop, program stops.So we need to check for that when we create our while loop like:
number_from_user = raw_input("Number: ")
while number_from_user != "stop":
try:
if int(number_from_user)% 2 == 0:
print "Even number"
else:
print "Odd number"
number_from_user = raw_input("Number:")
except ValueError:
print("Enter a number please")
number_from_user = raw_input("Number:")
And I suggest you make yourself familiar with while loops, which I found a video explaining and making an example "Guess the number game" using python. It should help you enough to make you able to solve your own problem with while loops.
https://www.youtube.com/watch?v=tu0zlBFRa_c
or:
https://www.youtube.com/watch?v=PoPxclbw6uc
And I suppose you're using python 2.7, in those videos they're using python 3+, you should type raw_input where they're typing input.
Edited: Added try and except.

How would you exit a loop with a string literal in Python?

For some reason, I get a NameError exception raised when I try to execute this code:
while True:
fileString = input("Enter your command: ")
print(fileString)
if fileString is "end":
break
else:
print("\nSomething went wrong! Please try again.")
continue
print("The program will now shut down.")
I would like to break the loop when "end" is entered in the input.
Two things to note here.
(1) Use raw_input(), and not input(). With integers, input() will be ok
But you seem to be entering string.
fileString = raw_input("Enter your command: ")
(2) Change the if statement to
if fileString == "end":
if fileString is "end"
That line is your problem, compare fileString's equality to "end" with == (tests for value equality) and not is (tests for pointer equality).
On a side note, I suggest removing the redundant continue on line 8.
In Python, 'is' tests for identity. To test for equality, replace the 'is' with '=='. It may work then.

How to get a string value in input as invalid?

I've been playing around with strings and I've found that when one inputs a string into a input function it gives an error.
I was wondering how to print "invalid" if a string was typed for an input variable. I want to do this the simplest way possible and the function should be the input and not the raw_input and I don't want to use try or except because that would complicate the code I'm planning to create.
testing_variable = input ("enter a number:")
# if a string is entered print invalid
if testing_variable == "":
# the "" is what im using if a string is entered and im having a hard time solving this
#Tips or advice of any coversion of the input would be helpful
print "invalid"
Using the input function in Python 2 is generally a bad idea. It is equivalent to eval(raw_input()), and thus expects the user to input a valid Python expression. If they type in something that is not valid Python, you'll always get an error.
While you could catch various exceptions and translate them into useful error messages, a better approach is to use raw_input and do your own validation for the specific types of input you want to be able to handle. If you only want to accept numbers, try converting the string you get from raw_input to int or float (and catching ValueError exceptions which indicate non-numeric input). For your desired result of printing "invalid":
try:
result = int(raw_input("enter a number"))
except ValueError:
print "invalid"
This is the most Pythonic way to solve the issue. If for some reason you don't want to use exception handling, you can save the string you get from raw_input and analyze it first to make sure it has only the characters you expect before converting it to a number. For base 10 integers this is not too hard, as only digits need to be checked for, and the isdigit method on a string will check if it contains only digit charaters:
str_input = raw_input("enter a number")
if str_input.isdigit():
result = int(str_input)
else: # string contains non-digit characters
print "invalid"
It's quite a bit more complicated to validate the input string if you want to support floating point numbers, as there's no convenient function like isdigit that will check all the characters for you. You could do it if you really wanted to, but I'd strongly recommend going with the exception catching code style shown above and just passing the string to float to see if it works.
Python 2.7 supports input and raw_input.
So, with input, you are expected to wrap your input with quotes. If you are wanting to avoid this, then use raw_input.
Example with raw_input:
>>> raw_input('hi ')
hi hey
'hey'
If you are looking to force the user to always enter a digit, then you can wrap it in a try/except as such:
try:
i = int(raw_input("Enter a number: "))
except:
print("you did not enter a number")
This is the best way in my opinion:
testing_variable = input ("enter a number:")
try:
number_var = int(testing_variable)
print(number_var)
except ValueError:
print("Invalid")
Without using try you can do:
testing_variable = input ("enter a number:")
if not testing_variable.isdigit():
print("Invalid")

Python program isn't displaying an output [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I determine if user input is a valid hexadecimal number?
Python - Program not displaying as intended
#Hex Check
def Check(HexInput):
while True:
if HexInput in Valid:
print('That is a valid hex number.')
else:
print('That is an invalid hex number.')
return HexInput
HexInput=input('Enter a hex number: ')
Valid='1234567890ABCDEFG'
Program needs to contain Check(). It should ask the user to input a hex number and tell them whether it's a valid hex number or not.
First of all,
while False:
will never execute. You can use "while True:" or "while checked == False:" but not "while False:"
Your Check() function must also take in parameters so that it looks like
def Check(UserInput, Valid):
You also need an additional "if" statement because even if the user inputs an invalid hex value, the program will still print "That is a valid hex value."
Next,
return Check
does not make sense as you do not have any variable named "Check"
Finally, you must actually call your function like so:
Check(UserInput, Valid)
It is not clear what you want to do in your program but for start , while False: mean that the code in the while loop will always be ignored (not executed)
The body of the while False: will never execute.
while False:
print("You will never enter this loop.")
.
.
.
This will execute, but you have to make sure you test for a condition,
so you can break out of the loop. That is you do not want to loop endlessly.
while True:
print("You will enter this loop.")
print("Make sure you test for a condition that will let you "break".)
break
Edit: You asked me to check your program. There are still some problems.
Use raw_input instead of input. The Python Tutorial at http://docs.python.org suggested raw_input.
The way you've written your program, if you have a multi-digit number, you'd need to check each digit, and that's what Python's for is for.
I've written something crude. In my version you'd test for 0 or non-zero. If
zero, you don't have a hex number. I'm sure there is a more elegant way to do this.
I strongly suggest fiddling with code in the Python command line. That's what it's for.
def Check(HexInput):
valid_hex_digit = 0 #Assume invalid
for digit in HexInput:
if digit in Valid:
valid_hex_digit = valid_hex_digit + 1
else:
error_str = "Invalid hex digit " + str(digit) + " found."
print(error_str)
valid_hex_digit = 0
break
return valid_hex_digit

Beginner: While loop not functioning properly, syntax errors, displays nothing

I am working through some Looping exercises, While statements in particular. Here are the instructions:
2.2) Modify the program so that it asks users whether they want to guess again each time. Use two variables, number for the number and answer for the answer to the question whether they want to continue guessing. The program stops if the user guesses the correct number or answers "no". (In other words, the program continues as long as a user has not answered "no" and has not guessed the correct number.)
Here is my code:
#!usr/bin/env python
#
#While statement
number = 24
while number != 24:
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if number == 24:
print "You got it! That is great!"
elif answer == "no":
print "Thank you for playing."
else:
print "That is not the right answer! Try again."
When I run the module in IDLE, the end quote of That is great!" - becomes red and says invalid syntax. In terminal if I run $ python while.py nothing loads. I've tried writing this as Python 3 functions with print("") but it still does not run.
Thanks to anyone who can help with this.
The while-cycle is never entered because the condition number != 24 never holds.
This is why there is no output.
Your loop never executes because you state that number = 24, and then right after, your while loop will only start if number != 24.
In addition, raw_input will yield a string, not an int so either ask for "24" or cast the raw_input to an int.
It also seems that you don't actually give the user a chance to guess the number at all; you only ask the user if s/he wants to keep playing.
You might want to do something like this:
number = 24
answer = ""
while answer != str(number):
answer = raw_input("Guess my lucky number, or type 'no' to quit.")
if answer == "no":
print "Okay, see you later"
break
elif answer != str(number):
print "wrong number"
if answer == str(number):
print "you got it right"
Here's the syntax issues:
answer = ""
while answer != "24":
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if answer == "24":
# You can fill in the rest ...
Well, I don't want to straight out solve it for you, but take a look at your conditional in the while loop. Think about what happens, line-by-line, when you run it, particularly in the "number" variable.
The other answers are touching on the problem but there are more...
Yes you really should be checking the answer variable in your loop instead of the number variable, but also keep in mind that raw_input is going to give you a string. So you will not get an int 24, you will get a string "24". The idea here is to take the answer variable from raw_input and check that variable against both your number and the value "no"
number = "24"

Categories