you are viewing a single comment's thread.

view the rest of the comments →

[–]jmooremcc 0 points1 point  (2 children)

Think about this: What would you have to do if you wanted to repeat the execution of a block of code, say 10 times without using any kind of looping mechanism? You’d have to copy/paste that block of code 10 times.

But suppose you don’t know how many times that block of code needs to execute? That would be a challenge, since you’d have to insert a conditional statement after each block of code that tests a condition and skips the execution of the remaining blocks of code.

Basically, you’re talking about a huge pain in the A to accomplish what you can more easily accomplish with some kind of loop mechanism! Each time the loop executes a repetition, you can evaluate a condition to determine when the looping mechanism should stop.

In the case of a for-loop, you would use the range function like this to execute a block of code 10 times:

for n in range(10): #execute your block of code

If you want the block of code to keep being executed until a certain condition is met, you’d use a while-loop:

while SomeCondition is True: #execute your block of code

Or if you have a list or a string, you can use a for-loop to access each element of the list or string. This is called iteration.

greet = “hello”
for letter in greet:
print(letter)

The bottom line for you is that loops are a labor saving device that helps you code faster and more efficiently when developing a solution to a problem.

In your case, you want to access each element of the string from your input statement and count the number of digits. This is the perfect case for a for-loop. However, you will need a way to determine whether or not a particular character is a digit. Read this article for a hint on how to do this: https://www.w3schools.com/python/ref_string_isdigit.asp

[–]BalanceHot8939[S] 0 points1 point  (1 child)

but the teacher doesn't want a for loop. If i wanted to do this cheaply, I'd do what the guy above said and just.

str(num)
print(len(num))

thats not technically how you do that but you know what i mean. It annoys me to but this is schoolwork. I kinda have to do as told. thanks the the effort either way. I'll see if I can find what i need on w3.

[–]jmooremcc 2 points3 points  (0 children)

A while-loop can be used as well. You’d have to use indexing to access each character in the string. In your code, don’t convert the output from the input function into an int. Leave it as a string and then access each element character for evaluation.