Defining the same variable twice / help understanding - python

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.

Related

Looping and Lists - BaSe fOO ThE AttAcK

In the war against Skynet, humans are trying to pass messages to each other without the computers realising what's happening.
To do this, they are using a simple code:
They read the words in reverse order They only pay attention to the words in the message that start with an uppercase letter So, something like:
BaSe fOO ThE AttAcK contains the message:
attack the base
However, the computers have captured you and forced you to write a program so they can understand all the human messages (we won't go into what terrible tortures you've undergone). Your program must work as follows:
soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
code: soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
says: destroy their ice-cream supplies ​
Notice that, as well as extracting the message, we make every word lowercase so it's easier to read.
Could you please help me with my code? This is my code so far:
output=[]
b=0
d=0
code=input("code: ")
code=code.split()
print(code)
a=len(code)
print(a)
while b<a:
c=code[b]
if c.isupper:
output.append(c)
b=b+1
elif c.islower:
b=b+1
else:
b=b+1
print(output)
I need the last line to say "BaSe ThE AttAck" eliminating "fOO" and I will be reversing the string in the last step to make sense, but it is not differentiating between a lowercase word and an uppercase word.
I have rewritten your code.
#code=input("code: ")
code = "soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess"
code=code.split()
output = []
for word in reversed(code): #iterate over the list in reverse
if word[0].isupper(): #check if the FIRST letter (word[0]) is uppercase.
output.append(word.lower()) #append word in lowercase to list.
output = " ".join(output) #join the elements of the list together in a string seperated by a space " "
print(output)
output
destroy their ice-cream supplies
Here's My answer, Tested on grok learning and green across the board:
code = input('code: ')
code=code.split()
output = []
for word in reversed(code):
if word[0].isupper():
output.append(word.lower())
output = " ".join(output)
print('says:', output)
There are two issues with your code:
isupper and islower are methods, i.e. you need to call them by writing ().
c.isupper() will check if the entire word is upper-case. However, your problem description says to just consider the first character of each word. Hence, try using c[0].isupper().
Now, after that has been fixed, you're still left with reversing the output list (and making each word lowercase) but I suppose you didn't get to that just yet. :-)

Python guessing word game

I trying to convert my code using function. As this coding is not done yet but i manage to get the code running well. The only thing is every time i guess a letter, it reset my previous record. How to i store my previous guess result and continue add if the letter is guessed correctly?
import random
def chooseAword(wordList):
correct_word = random.choice(wordList)
return correct_word
#def spelltheword(word)
def guessAletter(guessedletter):
word = guessedletter
guess = input('Guess a letter: ')
letter = ''.join(x if x in guess else '-' for x in word)
if guess in word:
print("So far you have: ", letter)
else:
print("So far you have: ", letter)
return letter
def playAgame(wordList):
word = chooseAword(wordList)
for n in range(5):
guessletter = guessAletter(word)
def main():
wordList = ('python', 'csharp','java','oracle')
playAgame(wordList)
main()
No, it doesn't reset your previous record: you have no previous record. Every call to guessAletter very specifically puts a hyphen in any position that is not the currently guessed letter.
Yes, you return the word (which you named letter, for some reason) of hyphens and correct letters, but the calling program playAgame puts this into a local variable guessletter (another misleading name), and then never uses it again.
I have several suggestions:
Practice incremental programming. Write a few lines of code to perform a trivial part of your program. Debug them. Do not continue until you know they do what you want, through testing several possibilities. Then write a few more lines; repeat this process until your program works.
Use meaningful variable names. word doesn't tell us much; we don't know whether this is the word we're supposed to guess, the current game progress you show the user, or something else. At the worst, you use guessedLetter for something that is not a single letter, and is not a guess.
With the incremental programming, follow the status of your game state: this should be one value passed back and forth with your guess-and-check function. You update it in that function, and print it in the guess-a-letter loop.

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.

I do not understand this piece of tutorial code?

I'm currently learning Python from a book by Michael Dawson. Everything was clear and concise except when i got to an exercise called the 'Word Jumble Game'.
This is the code that is confusing me.
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
What i don't understand is how the while:word works. This is the explanation given:
I set the loop up this way so that it will continue until word is
equal to the empty string. This is perfect, because each time the loop
executes, the computer creates a new version of word with one letter
“extracted” and assigns it back to word. Eventually, word will become
the empty string and the jumbling will be done.
I tried tracing the program (maybe its an obvious oversight on my behalf) but i cannot see how the 'word' eventually breaks out of the loop because as long as it has characters in it surely it would evaluate to True and be an infinite loop.
Any help is hugely appreciated guys as i have looked for answers everywhere and its been fruitless. Thanks in advance.
This three statement is what you are suffering to understand
jumble += word[position] # adding value of the index `position` to jumble
word[:position] # items from the beginning through position-1
word[(position + 1):] # items position+1 through the rest of the array
So, after each iteration, exactly one item is cut down from the original string word. (word[position])
So, eventually you will end up with an empty word string.
if you are not convinced yet, add a print statement at the end of every iteration. This should help you.
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print word
while word: Loop block will be executed until word length is zero.
Note: This code acts like random.shuffle. from random import shuffle; shuffle(word)

What is wrong with the ordering of this code?

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.

Categories