I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len("original")
if length > 0:
print original
else: length < 0
print "empty"
Notice that print under else is not indented. I thought you had to indented it, but when i do it gives me an error.
You seem to have a couple issues with your code. First I believe you should change your assignment of length to:
length = len(original)
That way you get the correct length of the string you binded to the name original. If you use len("original"), you will pass the string "original" to the len() function, and it will just count the characters in that string. Regardless of what the user of your program inputted, your length will always be 8, since that's how many characters are in the string "original"
Also keep in mind that the len() function will never return a negative value. So testing if length < 0 doesn't make sense. You probably wanted to test if it equals 0. It seems as if you were trying to use an elif statement.
Try:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
elif length == 0:
print "empty"
elif statements let you test conditions just like if statements. elif is short for "else if".
Furthermore, as #chepner pointed out in the comments, there is no need to even test the second condition at all. You can just as easily go with:
else:
print "empty"
The else syntax is not followed by any condition. It automatically enters the indented block of code if the other conditions evaluate to False.
Was the length < 0 intended to be a comment? You need the comment character #.
else: # length < 0
print "empty"
It's wrong anyway, it should be length <= 0.
Without a comment character it was being interpreted as the statement to use as the else clause. It didn't create an error since length < 0 just generates a boolean result that you didn't do anything with, but it prevented you from having another statement as part of the else.
else: length < 0
print "empty"
should be
elif length == 0:
print "empty"
Python has significant whitespace, things that are indented the same are in the same scope.
First off, it is not len("original") it is len(original). If you use quotes you are making it a constant value, "original", rather than a variable named original.
Second, instead of checking the length of the string you should use this
if original:
# Type here what happens if the string is not empty
else:
# Here what happens if the string is empty
By Python standard any collection, including strings, equals false if it is empty(aka contains no elements) and true if it contains any elements.
There is a a statement after else.
else: length < 0
print "empty"
Maybe you are looking for an (elif is another way to check another condition after the if if the previous if fails.)
elif length <= 0:
or just a plain
else:
print "empty"
it will never go past zero anyways you could have a == conditional for zero and it would work.
elif length == 0:
this is probably the best way there is no need to check another condition.
if length > 0:
print original
else:
print "empty"
also just a side note length = len("original")
there is not suppose to be quotation marks around original because its a variable :). You will just be getting the string "original" not the actual stuff inside of the variable.
The end result ..
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
else:
print "empty"
To check if there is an item in a list, simply do this:
if List_name:
{code here}
...
So, your code should very simply look like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
if original:
print original
else:
print "Empty"
It's that easy :D
Related
The use of parentheses for 'if' loop results in two different output for a palindrome program!
1.) () this gives the accurate result
2.) [] this only gives you the result of 'if' statement even if the "String" is not a palindrome
def isapalindrome(String):
if(String == String[::-1]):
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes properly!
def isapalindrome(String):
if[String == String[::-1]]:
return("is a palindrome!")
else:
return("is not a palindrome!")
String = input("Enter the String of your choice: ")
isapalindrome(String)
this code executes only the 'if' statement!
() and [] are nothing alike.
() does what you expect it to, but wouldn't even be necessary since there is only one operator.
[] will create a list with a single element that equals the truth value of String == String[::-1], so either [True] or [False]. Independently of what the list contains, non-empty list in python are truthy. This means that your if condition will always evaluate to True
As other comments suggest, the correct structure of an if statement is:
if condition:
print("Do something")
else:
print("Do nothing")
Parenthesis are useful when using boolean expressions:
if (A==B) == C:
print("Do")
Point being, the brackets '[ ]' do not really belong there. As they are used to select a memory space within a given memory slot. Just like we would do with arrays.
I think is good that you are exploring different things, it is always good to know why things are the way they are.
Your program should ask the user to input the list, then it should call the function, and print the result. with the following condition:
It returns True if the given list has at least 2 white spaces and False otherwise.
My code:
n = ((input("Please input a list of numbers separated by space:")))
t = 0
k = n.count(' ')
for i in range(0,len(n)):
if n[i] > " ":
print("True")
else:
print("False")
print("There are",k,"space which has two length run")
My program counts all of the white spaces, but I want it to only count the 2 white spaces or more and return True or False otherwise
I see several issues with this code.
First, you do not define a function as stated in the requirements.
Second, k = n.count(' ') already counts all the spaces in the input string. You do not need to loop over each character.
Third, even if you did need to loop over the characters, n[i] > " " is definitely not the right way to do what you want.
Fourth, what is the purpose of the t variable?
Fifth, why is input() enclosed in two extra layers of parentheses?
Not clear why you think you need a loop.
Try simply
print(n.count(' ') >= 2)
Or rather
def foo(n):
return n.count(' ') >= 2
print(foo(input("Enter some numbers:")))
I am trying to make a python program that
1. compares the first and last letter of a word
2. tell whether the words inputted to the program are in alphabetical order
e.g.) alaska baobab cadillac => would pass
e.g.) alaska baobab greg => would not pass
my code is shown below
num_words = int(input())
while num_words > 0:
my_word = str(input())
num_words -= 1
alphabet_order = ord(my_word[0].lower())
if my_word[0].lower() != my_word[-1].lower() or alphabet_order != ord(my_word[0].lower()):
print(my_word)
break
alphabet_order += 1
if alphabet_order == ord('z') + 1:
alphabet_order = ord('a')
else:
print('no mistake')
Hi everyone on stack.
I am pretty new to programming and I am starting to find assigning variables within a loop very cumbersome.
It seems like my variable alphabet_order keeps getting renewed every time when the loop takes in a new input.
What would be a great way to steadily increase the alphabet_order variable by 1 while only renewing ord(my_word[0]) every loop?
Few notes, while loops are good for when you don't know how many times you are going to loop. for loops are good for when you know how many items you are looping. In this case we have a known number of words we are to check so using a for loop makes more sense. This way we don't need to take an input on telling us how many words we expect.
Also your code wasn't dealing with the words you were dealing with the sentence, so instead you should split() your input by the space to get a list of the words to operate on. for loops can iterate through a list which is useful for us.
Note that for loops also can take an else, the else section runs after the for loop is finished all the elements it's iterating through and we know that if the for is finish all the words in the list, then the else section will kick in. If we break out, then the else doesn't run.
The rest you more or less had it, just need a starting ord('a') would have made life easier.
my_word = input() #take a sentence such as alaska baobab cadillac
current_ord = ord('a')
for each in my_word.split(' '):
if each[0].lower() != each[-1].lower() or current_ord != ord(each[0].lower()):
print(f"bad word {each}")
break
current_ord += 1
if current_ord == ord('z') + 1:
current_ord = ord('a')
else:
print('no mistake')
Maybe this is helpful to you. Instead of initializing it inside the loop, declare it outside the loop and assign it differently based on the conditions.
Tip: having while num_words > 0 is redundant because it will terminate automatically when it hits 0 as it is treated as False. And there is no need to convert int to a str type as it is str by default.
num_words = int(input("Enter a number"))
alphabet_order = None
while num_words:
my_word = input("Enter a word")
num_words -= 1
if alphabet_order is None: # happens only once
alphabet_order = ord(my_word[0].lower())
if ord(my_word[0].lower()) >= alphabet_order:
print('ok')
alphabet_order = ord(my_word[0].lower()) # update alphabet_order
else:
print('not ok EXITING')
break # closing loop
I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.
def palindrome(strA, strB):
if (strA == strB and strA[::1] == strB):
print "true"
else:
print "false"
if __name__ == '__main__':
palindrome("sirap", "paris")
In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?
You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:
if strA[::-1] == strB:
print "true"
else:
print "false"
What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.
You could even do it in one line:
print ("false", "true")[str[::-1] == strB]
I did a similar test using the "100 projects" to learn python (useful for learning any language)
You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.
print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string
if revstring == inputstring2:
print "Yes: " + revstring
else:
print "No: " + revstring
So the code below takes an input and makes sure the input consists of letters and not numbers. How would i make it also print orginal if the input contains a space
original = raw_input("Type the name of the application: ")
if original.isalpha() and len(original) > 0:
print original
else:
print "empty"
tried this code but worked when the input was a number too.
original = raw_input("Type the word you want to change: ")
if original.isalpha() or len(original) > 0:
print original
else:
print "empty"
It looks like that's just how string works.
Two options:
if all(x.isalpha() or x.isspace() for x in original):
(modified on inspectorG4dget's recommendation below)
or
original.replace(' ','').isalpha()
should work.