How would you exit a loop with a string literal in Python? - 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.

Related

Detecting the input of a carriage return in the console

A requirement for a school assignment I have asks that when a carriage return (\r) is entered as an input, it is used to halt the program: "if only a carriage-return is entered, halt the program". I've tried several things, but am stumped as to the solution.
Below are the options I've checked, all of which fail the running tests.
while input != '':
while input != '\r':
while input != '\n':
Thanks!
input is a function. You have to write input().
However, I assume you are actually trying to read information from the user, and exit if they entered nothing. Your statement while input() != '': won't do that, because if they enter something useful, it will be thrown away. You haven't stored it.
You PROBABLY want something like:
while 1:
line = input()
if not line:
break
# Now use the contents of line.

Currency Converter program IF/Else Statement

I'm trying to write a currency converter program on Python and I seem to have trouble on my IF/Else statement. I wrote "Do you want to convert?" as a question and if answer begins with "y" then the user will begin program. Same with if answer is "n" then the program will exit. But now i'm trying to write a statement where if any other letter is written else than "y" or "n" then a message saying invalid answer will come up. So far it looks like this:
answer=float(input('Do you want to convert?'))
if answer.lower().startswith("n"):
print("Goodbye "+name)
exit()
elif answer.lower().startswith("y") or ("Y"):
Amount=int(input("Enter amount to convert:"))
currency_1=input("Currency you want to convert from:")
currency_2=input("Currency you want to convert to:")
else:
print('Sorry. Invalid answer. Please start again')
First, your question is going to cause an error because you are asking the user to input a string, and then trying to convert it to a float, which does not work. Line 1 should just be
answer = input("Do you want to convert?")
Next, it may just be a formatting error in your question, but your if statement is not working because you need to indent the lines within the statement.
change the elif to:
elif answer.lower().startswith("y"):
Since the string is already changed to lower case, the "Y" comparison will never match.
use an infinite while loop:
while True:
answer=str(input('Do you want to convert?'))
if answer.lower()[0] == 'n':
print("Goodbye "+name)
exit()
if answer.lower()[0] == 'y':
break
print('Invalid answer')
Why did you convert your input answer to float and then treat is as a string?
Try this:
answer=str(input('Do you want to convert?'))
if answer.lower().startswith("n"):
print("Goodbye "+name)
exit()
elif answer.lower().startswith("y") or ("Y"):
Amount=int(input("Enter amount to convert:"))
currency_1=str(input("Currency you want to convert from:"))
currency_2=str(input("Currency you want to convert to:"))
else:
print('Sorry. Invalid answer. Please start again')

How to verify numbers in input with python?

I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb

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