My code runs through fine if I enter a word, but if I want to test the "else" part of it by not entering anything and just hitting enter when asked for a name, it returns "Oops, try again! Does your code print "empty" when len(original) is 0?"
To explain, I'm trying to complete a course on codecademy.
I've looked around and I just don't see why it shouldn't print "empty" into the console. Anyone got a clue? Does the fault lie with the lesson or is there really a mistake in the following code that'd keep it from printing the "empty" to the console?
print "Welcome!"
original = raw_input("Please enter a word")
if len("original") > 0:
print original
else:
print "empty"
You are checking the length of a string literal "original", which will always be greater than 0.
if len("original") > 0:
change this to...
if len(original) > 0:
Change ("original") to (original). When something is in quotes, Python evaluates it as a string. So here, you are simply checking the length of the word "original" which is always going to be larger than 0. If you put in (original), Python will evaluate it as a variable that you defined previously.
In a nutshell: you want the function to evaluate a variable, not a string literal (which is defined by "").
Related
So I am trying to write a simple code that will do the Pythagorean theorem for me after I input A, B and C but the code is skipping my While statements, and I have tried rewriting them as if statements to see if that works and again it will skip it, I need some help Please and Thank you Btw I do realize that in the picture that my while loops are open and have nothing ending them but I did have that in there at one point but I had taken them out when I changed to If statements.My Code I cant seem to understand
When you use input() the input comes as a string, and in your while loop you set your condition to be equal to 1 (as an integer).
A solution to this would be:
varname = int(input("")) #this way it converts your input into an integer
When you're taking input() from the user, it is returned as a string. Suppose user enters 1 it will be stored as "1" # which is a string. Now when you compared Yes_No == 1 it returned False because "1" == 1 is False.
So you need to parse (convert) it into a number (integer), which can be done by passing string to int() function. It will return the integer representation of that string. Do the same with all the inputs and your problem will be solved!
Another problem with your code is that you're not updating the value of Yes_No in any of the while loop. Which means that it will result in infinite loop, it will keep executing the while loop because once the condition becomes True it will not become False because value of Yes_No is not updated.
As the python documentation points out, the input function returns a string:
input([prompt])
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
If you didn't know that and you wanted to debug and figure out, you can do something like print(type(Yes_No)) and you can see that it is a string type, so when you evaluate this expression: while Yes_No == 1, it returns false.
So the fix in this situation is to change your input line to
Yes_No = int(input("Do you have the hypotenuse? For yes press 1 or for no press 2"))
Python 2.7
I was writing code for the PygLatin Translator.
Here's my code:
print"Welcome to the English to Pig Latin translator!"
original=raw_input("Enter a word to translate. Any word.") #Takes an input
if not original=="" or original==" " and original.isalpha()==True: #Checks that 'original' is not an empty text field and also is not a number.
print original #If both conditions are true then prints 'original'
else: #If both conditions don't come out true then prints an error.
print"Either the field is empty or your entry was a number."
If I give 123 as input, it still prints 123, even though it is a number. It is supposed to execute the else block if the input contains numbers. What's the problem with my code? Please explain in simple words as I am only a Python beginner.
Your boolean logic is incorrect; the if statement executes as:
(not original=="") or (original==" " and original.isalpha()==True)
because or has a lower precedence than and (see the documented precedence order).
Because your string is not empty, not original=="" is True, and the second part of the expression isn't even evaluated anymore.
The test can be simplified and made correct with:
if original.strip().isalpha():
because str.isalpha() never is True for empty strings. In the above expression, str.strip() removes all whitespace from the start and the end of the string, leaving an empty string if there was only whitespace in it.
You are printing your input statement, your input statement is original so if you want to print something else replace original in the if statement with what you want to print
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
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
For some reason I'm having trouble getting my program to run a while loop.
No error messages, just that it stops the program. I tried having it print "hi" as the first instruction, but it didn't, so I know it's not even running the loop. Here's a bit of code (Note: The testing for correct values works fine, but the loop won't use these correct values!)
print "current letter value:", letter_value
print "letter:", letter
print "number:", number
while letter!="$" and number<=5 and number>=1:
print "hi"
//all the stuff in here
I know it should be an infinite loop, but it won't run at all!
Input:
letter is 'A'
letter_value is 1
numberis 1
My loop ought to test to make sure that letter isn't $ and that the number is <=5 and number >=1
you didn't give the print out for letter and number, it could be that the "number" is actually a string?
Your syntax is fine. Without seeing all of your code, I generically recommend that you might want to make sure there aren't any invisible whitespace characters that are breaking you out of the loop unexpectedly. Also verify that 'letter' and 'number' are have values that will make the while conditions happy (e.g., if 'number' is 0, then it won't kick off).