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.
Related
This doesn't really work
To explain what I did:
I set a vowel variable with a list
Then I used a for loop to iterate through the list and print the letters not in the list
as user #user56700 noted: You did, probably by mistake:
if not letter.lower in vowels:
instead:
if not letter.lower() in vowels:
first is method "itself", second is call of method.
P.S.
also, as user #user56700 noted, do not screenshot and paste code as image. Just paste and format as code, it is really simple, and shows that min of respect for others :)
import re
vowel = input()
lst = re.sub("[aeiouAEIOU]","",vowel)
print(lst)
`
st=input("Enter Any String ")
vowel=['a','e','i','o','u']
#Create a List of Vowel
st=st.lower()
#Convert Vowel in Lower case
output=""
for i in st:
if i not in vowel:
#Check Vowel if not then add to output
output+=i
print(output)`
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'
I'm trying to make a program deciding what determiner comes behind the input.
#For now, this only works with letters A-D.
MyInput = input("What word do you want to find out if the determiner is a/an?")
Finder = list(MyInput)
if ('a' in Finder):
print ("Start with an.")
else:
print ("Start with a.")
However, there is a little bug. When I input the word "bad", it says I need to have "an" go before the word. I want it to only say I need to have "an" be before the word when the first letter is A. What's the solution to this problem?
It is because in checks if the character can be found anywhere in the string. When you use "bad" it can. If you are checking the first character use Finder[0]
MyInput = input("What word do you want to find out if the determiner is a/an?")
Finder = list(MyInput)
if (Finder[0].lower() == 'a'):
print ("Start with an.")
else:
print ("Start with a.")
Regarding the question, using str.startwith would be the most clear way to go:
# For now, this only works with letters A-D.
my_input = input("What word do you want to find out if the determiner is a/an?")
if my_input.startswith('a'):
print ("Start with an.")
else:
print ("Start with a.")
Pay attention to the fact you do not need to make a list from a string: strings are iterable, they support in and indexing out of the box.
Also note the readability improvements:
Name variables using snake_case
Start a comment with a space
Do not put a conditional into brackets
See PEP8, the python style guide for more issues and details about codestyle.
Cheers!
Okay, so I have gotten this far with a Caesar cipher program in python and cannot see any reason why this doesn't work, but it doesn't... it outputs the new word as 'a' 'a' 'a' (for however many letters were in the word). My guess is its some kind of loop that results in each letter being changed into 'a' but I just can't figure it out. Can anybody out there help me? Thanks.
My code:
word = input("please enter the word you wish to encrypt: ")
seperated = list(word)
length = len(word)
alphabet1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alphabet2 = ["b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a"]
length2 = len(alphabet1)
length3 = len(alphabet2)
for eachposition in range(length):
for letter in range(length2):
if seperated[eachposition] == alphabet1[letter]:
seperated.pop(eachposition)
seperated.insert(eachposition, alphabet2[letter])
print(seperated)
I added some print calls to your code and got lots of false positives where seperated[eachposition] == alphabet1[letter] was evaluating as True when it shouldn't. From that I realised the problem pretty quickly.
You never use break from your loop, so here's what's happening:
I enter "word"
The loop runs until it finds that the first letter is the same as the letter 'w' in alphabet
The first letter of separated is set as 'x', due to how your cipher works
The loop keeps running, now testing if the first letter is 'x'
Since your cipher just advances each letter on one, this loop will always run until it reaches the last letter in your list, 'a'.
The simple fix is to use break. It will end a for loop prematurely. Meaning that when you have replaced a letter, you want to break out of that inner loop and move onto the next character.
for eachposition in range(length):
for letter in range(length2):
if seperated[eachposition] == alphabet1[letter]:
seperated.pop(eachposition)
seperated.insert(eachposition, alphabet2[letter])
break
#SuperBiasedMan gave you the working solution for keeping your code, but i would propose a simpler loop for your task(no need for poping and inserting in place since you are iterating orderly in the whole word).
new = []
for c in word:
for i in range(length2):
if c == alphabet1[i]:
new.append(alphabet2[i])
break
new = ''.join(new)
print new
Also consider using dictionaries. They come in handy for problems like that.
Another approach is to convert each character to its ASCII number, ie a = 97, b = 98 etc asciitable.com This can be done with ord()
num = ord(character) - 97
Then you can add the key to obtain a new ascii code and convert it back to a character. You have use modulo to allow for cycling around from the end to the start of the alphabet.
encr_char = chr((num + key)% 26 + 97)
You need to add code to handle upper case letter (ascii 65 - 90) and non alphabet characters. isupper() and isalpha() will do the job here.
This approach allows for varying the key.
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.