What is wrong with the ordering of this code? - python

I'm trying to make a Pig Latin translator in Python. I don't have the finished product yet and I'm working through Codecademy. Here is my code so far:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
if first == "a" or "e" or "i" or "o" or "u":
print "vowel"
else:
print "consonant"
else:
print 'empty'
word = original.lower()
first = word [0]
I'm pretty sure the last two lines are out of place, but I do not know where they should go and I don't know why. If anybody could explain that to me, that would be great. I'm just at the stage of this program where I want to check if the first letter is a vowel or consonant, I'm not at the translating part yet.

You're defining word and first after you check their values, so try moving those after you define original and after you check the length (to avoid an index error on empty values).
Also, where you use if len(original) > 0, you actually simplify that to if original, which will return True if it is a non-null value.
One other thing - your check for vowels will not return the expected value. Instead, try something like this:
if first in 'aeiou':
I'm sure there are better ways to handle it, but this should work for your case.
EDIT:
Changing the if statement to #Levon's method (which is much more Pythonic)

This line:
if first == "a" or "e" or "i" or "o" or "u":
Does not behave the way you expect. I actually answered basically this exact question a few days ago.
Let me know if you don't understand the explanation I gave there.

(1) Your if-statement could be rewritten in a shortened (and correct) version like this:
if first in 'aeiou':
I answered this with more explanation recently here for someone else working on the same problem as you.
(2) Re your question about where to place these two lines of code:
word = original.lower()
first = word[0]
Put them after your print original inside your if-statement. They convert your input word to lowercase, and then take the first letter of the word and assign it to the variable first which is then subsequently used to check for vowel/consonant.

Related

PYTHON: Whenever I input something, I want my code to print multiple possible possible values

The title explains it all, but basically I want my python code to output multiple possible input values, here's my code which might make it easier
word = input("Input a word/sentence").upper().title()
if word == "Yes":
print("Dar")
elif word == "No":
print("Jor")
elif word == "Maybe":
print("Jard")
elif word == "Definitely":
print("forswer")
elif word == "Absolutely":
print("Arsry")
elif word == "Perhaps":
print("Åsët")
elif word == "Of course":
print("Aresøt")
So how can I make it so whenever I input "Perhaps , Definitely" that it shows both? Whenever I do that it obviously doesn't print anything.
So you want it to output "Åsët, forswer" for the example?
A possible way is to first break the input string into a list of word by splitting on "," and trimming then leading and trailing spaces. Then for each word in the list, translate it.
The translation part is almost identical to the code you have right now, except instead of printing it, you can save it into a list. Finally, when you have all the translations, oncatenate the list of translated words with ", ".
You will need to search in the string, right now you are just comparing the whole string. So your check would look something like this:
if "Yes" in word:
print("Dar")
There are other optimal solutions for this, but this should get you started.
You would need to create a dictionary and then replace:
word_dictionary = {'Yes':'Das','No':'Jor','Maybe':'Jard','Definitely':'forswer','Absolutely':'Arsry','Perhaps':'Åsët','Of course':'Aresøt'}
And then use the following to do the replacements:
','.join([word_dictionary.get(x.strip()) for x in text.split(',') if word_dictionary.get(x.strip())])
For example:
text = "Yes, Of course, but, No"
Returns:
'Das,Aresøt,Jor'

How would you check if a letter/number/symbol is in a string? (Python)

Sorry for asking a fairly simple question, but how would I make it so that if a certain letter/symbol/number would "activate" an if statement when the letter (for example "a") is in the element. If I make
thestring = ["a"]
(And then add the if statement ^^)
Then it would work but if I add another letter or number next to it:
thestring = ["ab"]
(And then add the if statement ^^)
It wouldn't work anymore. So essentially, how can I fix this?
Sample Code:
thestring = ["fvrbgea"]
if "a" in thestring:
print("True")
Output: (Nothing here since there's not an else code I guess.)
As Klaus D. alluded to, your string is a list of one element ("fvrbgea"). That one element is not equal to the string "a". If you remove the brackets from thestring your code will execute the way you are expecting to.
if you want to just validate if a string contains letters/numbers/symbols you should use regex:
import re
string = "mystring"
#Validate numbers, lowercase letters, dashes
if re.match("^[0-9a-z-]+$", string):
print("True.")
else:
print("False.")
thestring = ["fvrbgea"]
for el in thestring:
if el.isnumeric():
print("Numeric")
elif el.isalnum():
print("AlNum")
# elif el.isPutSomethingHere
The python basic library have the "is" method to check the string.
Just put variable.isSomethingHere to see.
Example
And if you want to check if a specify letter is in the string, just follow the same logic, and in certain cases you will ned put another for in the initial loop
thestring = ["fvrbdoggea"]
control = list()
for el in thestring:
for c in el:
if "".join(control) != "dog":
if c == "d" or c == "o" or c == "g":
control.append(c)
print("".join(control))
you can automatize that, but, it's a bit hardeful and i don't wanna do, but with this you can take an idea

Why for loop not processing the entire input string?

I'm new to Python coding. I am enrolled in the online course DEV274X: Introduction to Python fundamentals provided by Microsoft.
For my first assignment, I had to write a code that processes a given string and prints the words whose first letter are greater than or equal to 'h' in a new line
Only using the following methods: for/in (iteration), input, if, else, .isalpha() method, .lower() or .upper() method. The string was "Wheresoever you go, go with all your heart" and the desired output was
My code and the output I got was
Can someone help me by telling me what's wrong with this code?
I think your code is correct just a small mistake.
The last line is
print(ltr)
which will print only 't', the last iterated letter. You have to change it to 'new' and check if it is >'h'
quote="Wheresoever you go, go with all your heart"
new= ''
for letter in quote:
if letter.isalpha():
new+= letter
elif new.lower() >= 'h':
print(new.upper())
new= ''
else:
new= ''
if new.lower() >= 'h':
print(new.upper())
quote="wheresoever you go,go with your heart"
newword=""
for letter in quote:
if letter.isalpha():
newword = newword + letter
else:
print(newword)
if newword[0].lower()>='h':
print(newword.upper())
newword=""
else:
newword=""
if newword[0].lower()>='h':
print(newword.upper())
this is a typical edge condition check. Your code rely on new letter to determine current word should be print out or not. "Heart" is the last word and it should be checked at the end of for loop.

Count Occurrences using for, in, and return

I have been trying to write the code for this program for a while now, but I just cannot figure it out. I am very confused. I would appreciate the help:
Write a function that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.
You will need:
A function declaration, with parameters.
A for loop.
An if statement.
A return statement.
What I have so far:
string_one = "I love coding!"
string_two = "I"
if string_two in string_one: print "Hi"
Considering the code you have provided, it indeed works if string_two is in string_one, meaning that your if-condition is correct. However, it will only run once, so if string_two occurs multiple times in string_one, it will ignore all other occurences and print Hi only once. As a result, you need to add your if-condition into a for-loop to catch all occurences of string_two in string_one.
string_one = "I love coding!"
string_two = "o" # changed to 'o' since it has more than 1 occurence in string_one
for letter in string_one: # look at each letter in string_one, one after another
if string_two in letter: # also possible: if string_two == letter
print "Hi" # print Hi when the letter is found
All that's left to do now according to your task is to wrap this code into a function with two parameters (ideally one parameter called sentence and another one called character or similar) and return something. However, I will leave figuring this out to yourself, good luck! :)
First off, let's note that this problem could be solved using str.count(thing_to_count). That's what you should use in general, but I see here you are probably asking for help on an assignement (generally discouraged on Stack Overflow, but I personally don't have an issue with it). Anyway, here's the code I made for this.
def count_in_string (sentence, thing_to_count):
times = 0
for word in sentence:
for letter in word:
if letter == thing_to_count: times += 1
return times
So:
Declare count_in_string as a function with the arguments sentence and thing_to_count.
Set times to be the amount of times thing_to_count_ appears in sentence (so far 0).
Loop through every word, and then letter in the sentence.
See if the letter is the thing_to_count, and if so add 1 to times.
Return times as the result.

Defining the same variable twice / help understanding

I made this simple Pyglatin translator in a Codeacademy learning exercise. Code is working fine, but need help understanding why.
The variable new_word is defined twice in the if statement. How does the code know to print the second definition of new_word instead of the first. Seems like it would make more sense for the final two lines of the if statement to read like-
final_word = new_word[1:len(new_word)]
print final_word
Full working code below-
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
print 'empty'
Can you keep redefining the same variable and it will always take the last definition given?
That's how imperative programming works. It says set the value of new_word to X. Then set the value of new_word to Y. Each statement does a particular thing, and the statements are followed one by one, modifying the program's state one by one.
You can contrast that with something like declarative programming in which you only define everything once, and the computer figures out in which order it needs to execute what in order to arrive at the result you described.
In this line you assign the concatenation of word, first and pyg to new_word:
new_word = word + first + pyg
After that, in this line, you chop off the first char:
new_word = new_word[1:len(new_word)]
You indeed use the same var new_word twice,
and the newest value (first char chopped off) overwrites the first one (first char still present).
B.T.W. the second line is needlessly complicated, it could also have been:
new_word = new_word[1:]
Maybe it helps to realize that a program variable isn't a mathematical variable, and the = in your program isn't a mathematical =.
a = 3 isn't a proposition meaning that a is equal to 3.
It is an action that puts the number 3 into a memory location labeled a.
So you can always put something else there.
Early languages used := (becomes) instead of = (is), and some languages still use <- to denote this assignment action.

Categories