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
Related
This question already has an answer here:
Unexpected empty strings within Python strings
(1 answer)
Closed 3 years ago.
I was just fooling around in the Python console when I noticed these four results of four simple one line statements:
1. "x".endswith("")
True
2. "x".endswith("x")
True
Then I tried to strip the white-spaces from the statement, when they gave me these results:
3. "x".strip().endswith("")
True
4. "x".strip().endswith("x")
True
How can all of the results be True? How can a string function return True for ending with both "x" and ""? Isn't this contradictory or am I missing something here?
Python 2.7 on PyCharm on Windows 10.
If you want to check if a string ends with a space try "x "
For example, "x ".endswith(" ") returns True, but "x ".strip().endswith(" ") returns False.
"" is an empty character, what you are trying to do wont work. The space character is presented like this: " ".
The .strip() function removes all whitespace at the start and end of the string it's called on. Your string, "x", has no whitespace around it, so it will not change in any way (you can check this by running "x" == "x".strip().
You are also checking whether it ends with the empty string, which every string in Python does!
Add some whitespace to your string (eg "x "), and use a whitespace character in your endswith call (eg "x . ".endswith(" ")) to get a good idea of how the strip() function works.
Apologies for the poor title, I don't know how else to describe my situation.
I wrote a small pattern matching function.
def substrings(input_str):
'''Generate all leading substrings of an input string'''
for i in range(len(input_str)):
return input_str[:i]
It should return a series of slices of a string. If the input was ABCD, it should output ABCD, ABC, AB and A.
When I tested this function in the python console (shown below), it behaves correctly and outputs all the expected strings.
for i in range(len(input_str)):
print(input_str[:i])
But when used in the body of my program its returning nothing at all. For example;
test1 = substrings('ABCD')
print(test1)
Outputs blank lines and I'm struggling to figure out why.
In the console, your loop first prints out a blank string when i==0. Then it continues to loop and print out each of the characters in the string.
In the function, you are returning up to the 0th element in the array, which is the same blank string the console printed on the first time through the loop.
To see better what is happening in the console, you might print the index too:
for i in range(len(input_str)):
print('{0} {1}'.format(i, input_str[:i]))
That's because the first thing your functions returns is empty string ''. So you are exiting loop after first iteration for i = 0 and your variable is empty string because of the fact that:
>>> s = 'ABCD'
>>> s[:0]
''
You are returning in a loop. So the return is the last statement that would execute in a function. That is when a return statement is reached, the control leaves the function. So in the very first iteration i=0, the control returns '' and exits the function irrespective of for-loop. In console the output is obtained because I'm console each line is interpreted one-by-one unlike the program being compiled at once. So console shows the output. Hope this answer helps you
The issue is occurring because you are trying to return information in a loop. When the return statement is called, it exits the function. What you should do is use the yield keyword. Try doing this
def substrings(input_str):
for i in range(len(input_str)):
yield input_str[:i]
# Then iterate through the function like so
function = substrings()
for i in function:
print(i)
Your code should be working fine now!
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"))
print "YOU HAVE CHOSEN TO REARRANGE YOUR THE WORD THAT YOU ARE ABOUT TO ENTER..."
word = raw_input ("FIRSTLY YOU MUST ENTER A WORD TO BE REARRANGED, ENTER IT HERE:")
character_save = word[1]
def anagram(word):
if len(word)>1:
print str.replace('a','b')
word = str.replace(word[1],word[3])
word= str.replace(word[3], character_save,1)
print word
anagram(word)
I tried to fix this on numerous occasions, the problem with the first time was that it would just replicate characters instead of replacing the positions, the second time I tried to store the position that I was going to replace in a variable but now it mentions that I have only one argument given (when it should be 2).
Would it be easier to do this with a list instead of a string?
The replace message that you are using is called on the string that you want to replace and not on the str type itself.
In your case that is the word parameter that you are providing.
So if you replace the instances of str.replace with word.replace your code will run. However, it doesn't create an anagram yet. The algorithm is still lacking.
I am a beginner in python. I came across this question in codewars.
Jaden is known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example :
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
This is my attempt (I am supposed to code using a function)
def toJadenCase(string):
l = len(string)
for i in range(0,l):
if string[i] == ' ':
y = string[i]
string[i+1] = chr(int(y)-32)
return srting
s = raw_input()
print toJadenCase(s)
When run, the following errors showed up
How can mirrors be real if our eyes aren't real (this is the input string)
Traceback (most recent call last):
File "jaden_smith.py", line 9, in <module>
print toJadenCase(s)
File "jaden_smith.py", line 6, in toJadenCase
string[i+1] = chr(int(y)-32)
ValueError: invalid literal for int() with base 10: ''
I couldn't understand these errors even after google-ing it. Any help would be appreciated. I would also be great if other errors in my code are highlighted and a better code is suggested.
Thanks in advance :D
As Goodies points out, string should not be used as a variable name
Following the Zen of Python, this is technically a function that does exactly what you're trying to achieve:
def toJadenCase(quote):
return quote.title()
Edit:
Revised version to deal with apostrophes:
import string
def toJadenCase(quote):
return string.capwords(quote)
First you have to understand that strings are immutable, so you cannot set a single character inside a string, but build a new string from the old one and replace the old one (this can be usually done still in one pass so it's not a big complication).
Second, for most of these kind of operations, it is much better to use the methods of the string object itself, rather than redo everything from scratch.
Said that, there is still some complication with the question, but a function that does what you want is in the module string:
import string
s="How can mirrors be real if our eyes aren't real"
newstring=string.capwords(s)
If you prefer (why?!) a DIY solution (using string methods):
newstring=' '.join([ss.capitalize() for ss in s.split()])
Note that using split without argument splits the string on any whitespace (e.g. tabs etc.), that I think is the desired behavior.
If you want to do this without using a function that already exists, this is how I would do it and I'll explain everything:
Assuming you get a string with ONLY text based words and all words start with a character*
def toJadenCase(string):
words = string.strip().split()
# This first strips all empty spaces around the words in the text and then splits the string by spaces (default) otherwise you can add a character inside split in order to split it at the character. This returns a list of words in the sentence.
li = [] # initialize empty list
for word in words:
word = chr(ord(word[0])-32) + word[1:]
# So there's a couple of things going on here.
# I could use .upper() to upper case something (like word[0].upper() + word[1:]
# in order to get it but I wanted to do it without the use of that.
# That being said, ord just figures out the ascii number and subtracting
# 32 makes it uppercase. chr changes it back to a string.
# Then it can be concatenated to the rest of the word.
# Strings can be treated as lists in python so word[0] and word[1:] works
Also, word[1:] just means from the 1st index to the end.
li.append(word) # this appends the word to the list
return ' '.join(li) # this joins all of the words in the list with a space
Now, if you want something a lot more concise (you can use .capitalize()):
def toJadenCaseShort(string):
return ' '.join([x.capitalize() for x in string.strip().split()])
which returns:
>>> abc("hello my friends")
'Hello My Friends'
Basically what it does is it uses list comprehension to strip and then split the words, capitalizes them, and then joins them with spaces!
Of course, you could just use string.title() as mark s. says but what's the fun in that? :)
Here is the answer that passed for me
import string
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces