While loop won't run in Python (beginner)? - python

For some reason I'm having trouble getting my program to run a while loop.
No error messages, just that it stops the program. I tried having it print "hi" as the first instruction, but it didn't, so I know it's not even running the loop. Here's a bit of code (Note: The testing for correct values works fine, but the loop won't use these correct values!)
print "current letter value:", letter_value
print "letter:", letter
print "number:", number
while letter!="$" and number<=5 and number>=1:
print "hi"
//all the stuff in here
I know it should be an infinite loop, but it won't run at all!
Input:
letter is 'A'
letter_value is 1
numberis 1
My loop ought to test to make sure that letter isn't $ and that the number is <=5 and number >=1

you didn't give the print out for letter and number, it could be that the "number" is actually a string?

Your syntax is fine. Without seeing all of your code, I generically recommend that you might want to make sure there aren't any invisible whitespace characters that are breaking you out of the loop unexpectedly. Also verify that 'letter' and 'number' are have values that will make the while conditions happy (e.g., if 'number' is 0, then it won't kick off).

Related

Unit testing for code isn't working for cs50 problem

I'm currently working on a Cs50 problem called Testing my Twitter. The code works very well and has no problems. But I'm having trouble trying to run a unit test on it.
this is my regular code that needs testing:
def shorten(word):
tweet = input("Input: ")
for letter in tweet:
if not letter in ['A','E','I','O','U','a','e','i','o']:
return letter
print()
And this is my unit test code:
import twttr
def test_twttr():
assert shorten('Hello') == 'Hll'
test_twttr()
I've run into a lot of errors and have reached this point in my code where it just says OK. I changed my code to have an error and I'm still getting the same message. Can someone please take a look and see what's going on?
You have several problems. You ignore the input word and instead prompt the user for a value. Then you return the first vowel found instead of removing that vowel from the word. You need to remove vowels and then reassemble a string for return. And its a trivial matter, but checking against a set is usually faster than checking against a list.
This operation can be done with a simple list comprehension instead.
def shorten(word):
return "".join(c for c in word if c not in {'A','E','I','O','U','a','e','i','o', 'u'})

"Expected an indented block" What to do?

I'm new to programming and don't know what this means. Please tell me what to do to my code for my assessment. It doesn't highlight the problem when I run it and I don't know what to do. Please help me.
To be honest, reading a Python tutorial would probably do you better. In any case, however...
Python is an indentation-based language. This means anytime you enter a new "block" (code that belongs to a statement), you need to indent your code by one level. Here are two examples, one incorrect and one correct:
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
This is a syntax error, since the print statement belongs to the if statement, and is therefore a new block. It should be indented, but in this case it wasn't, so it's an error.
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
print "This is printed in any case, since it doesn't belong to the above block."
Here is the fixed verion. Notice the four spaces in the beginning of the second line? That's called "indentation". Any subsequent lines indented to the same level will be part of the block. Generally, you press TAB to indent in your text editor. The last line, however, is not indented and will therefore run regardless of whether the if statement evaluates to True or not.

Repeating an input

I'm new to Python and have been working through some tutorials to try to get to grips with different aspects of programming.
I'm stuck on an exercise that is most likely very simple however I am unable to find the solution.
How do I create a program that reads one line of input and prints out the same line two times?
For example if the input was Echo it would print:
Echo
Echo
Any help with this would be hugely appreciated. I think I'm making a simple logic error but don't yet have the skills in place to recognise what it is.
The other answers seem logical enough, but what if you wanted to print it let's say a 1000 times or a million times? Are you really going to be typing print(variable) a million types? Here is a faster way:
j=input("Enter anything.")
for i in range(2):
print(j)
Here, I can change the value of range to whatever I want, and J will be printed that many times.
What happens here, is that the variable i loops upwards (an increment) to the number 2, so to explain it to a beginner, i travels t=from number to number. Where I put print(j) for every number i loops through until it gets to 2, J will be printed.
It sounds like you've been doing the input and output in one go:
print(input())
That works for doing a single echo of the input, but makes it a bit harder to repeat the same thing twice. An easy workaround would be to save the inputted text to a variable, which you can print twice:
text = input()
print(text)
print(text)
If you needed to do the input and doubled output with a single statement, you could use string formatting to duplicate the text with a newline in the middle:
print("{0}\n{0}".format(input()))
way complex right?(:D)
inp = input("Input something would ya? ")
print(inp)
print(inp)

if/else trouble - else not printing to console

My code runs through fine if I enter a word, but if I want to test the "else" part of it by not entering anything and just hitting enter when asked for a name, it returns "Oops, try again! Does your code print "empty" when len(original) is 0?"
To explain, I'm trying to complete a course on codecademy.
I've looked around and I just don't see why it shouldn't print "empty" into the console. Anyone got a clue? Does the fault lie with the lesson or is there really a mistake in the following code that'd keep it from printing the "empty" to the console?
print "Welcome!"
original = raw_input("Please enter a word")
if len("original") > 0:
print original
else:
print "empty"
You are checking the length of a string literal "original", which will always be greater than 0.
if len("original") > 0:
change this to...
if len(original) > 0:
Change ("original") to (original). When something is in quotes, Python evaluates it as a string. So here, you are simply checking the length of the word "original" which is always going to be larger than 0. If you put in (original), Python will evaluate it as a variable that you defined previously.
In a nutshell: you want the function to evaluate a variable, not a string literal (which is defined by "").

Python - my while loop is stopping itself

This is a homework question and it asks "Pick a word. Ask the user to enter a letter. Check how many times the letter is present in your word and output the number on the screen." So far I have written it as is and it seems to be working fine:
word = str("python")
letters = len(word)
attempt = str(raw_input ("Enter a letter: "))
while attempt in word:
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
attempt = str(raw_input ("Enter another letter: "))
while attempt not in word:
attempt = str(raw_input ("This letter is not present, enter another letter: "))
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
but occasionally if I am inputting letters the program will stop and no longer take any more inputs. What am I doing wrong? I apologize if the code is very sloppy and poorly written as I am new to programming. Thanks.
I'm not sure if this is what you're getting at, but your while loops will execute one after the other. They don't both apply all the time. So the first while means "keep doing this as long as the user enters a letter that is in the word", and that loop will keep executing as long as the user enters letters in the word. As soon as the user enters one letter that isn't in the word, the loop will end and things will move on to the second loop. Execution will never go back to the first loop. Likewise, once in the second loop, if you then enter a letter that is in the word, the loop will end. Since that's the end of the program, the program will end.
So if you enter a letter that isn't in the word, then enter a letter that is in the word, the program will end. Like if you first enter "x" and then enter "y", it will then stop.
I think what you really want is more like:
while True:
attempt = raw_input("Enter a letter:")
if attempt in word:
print "That was in the word", word.count(attempt), "times"
else:
print "That was not in the word"
Of course, this program will loop infinitely until you close it by pressing Ctrl-Break or the like.
There are some other issues with your code. You don't need to wrap "python" in str, since that already is a string. You also don't need to wrap raw_input in a string, since raw_input already returns a string. You define a variable called letters but never use it.
Also, you define word = "python" at the beginning, but then sometimes later you use the word variable, while other times you retype the string "python" in your code. It doesn't matter for this program, but in general it's a good idea to assing the variable once and use that everywhere; otherwise you'll have to change it in many places if you decide to use a different word, which increases the likelihood that you'll forget to change it in one place, and thereby cause a bug.
Finally, note that in and count operate on substrings, not just single letters. So entering "yth" as as your input will still work and give a count of 1. There's not necessarily anything wrong with this, but you should be aware that although you're asking for letters the person can type in anything, and substrings of any length will still be found in the "word".
The program is sequential with two loops. Once those loops have been passed the program ends.
Loop 1: run while the input is found in the word.
As soon as this condition fails, we fall through to loop 2:
Loop 2: run while the input is not found in the word.
As soon as this condition fails, we fall through to the end of the program.
So, if you enter a "bad" input once, then a "good" input once, the program will end.
What you want to do is wrap both loops into one, and use an if-else to decide which each particular input is.

Categories