Python other resources

Hello! I am completely new to programming. Everything was understandable until For Loops. The explanations are lacking to me. I tried other videos and site, it made me understand the topic more but it’s different when it come from the instructor himself like why the command variable has an empty string etc. Can anyone give me any resources that help you understand Python while also watching Mosh’s too? I am really worried that I am just doing this for the sake of doing, not learning which is bad because I want to change to a new career in line with programming.

Anything will help. Thank you

Hi @jlrae. So, there are many other resources that are relatively cost effective eg on Udemy. Having done many of these others, I must admit I always rely on Mosh’s courses (and have done many of his) as a solid guide on how to write good code. My suggestion would actually be to just work at the actual coding. Write a for loop, if it does not work, search around on the web, review Mosh’s videos etc. The best way to learn is to just get stuck into writing some code and figuring out why it is not working.

2 Likes

Hi @Paul ! What you said is true, but there is a point where you just don’t know what a piece of code does or doesn’t do and why is there, why is there an empty string, why do we have to increment the for loop/while variable, why does is start sometimes with 1 and so on. For absolute beginners like myself all the help given is really appreciated and I know if I figured it out by myself would be better but help is needed

Hi @Lt.Smith. Perhaps if you provide a specific example of what you struggle with I could assist?

Hi @Paul !
Well a specific example I have problems implementing code, meaning I know, sometimes, what to do, but don’t know how to start, which line o code to write .
Another example: lambda function, honestly right now seems complicated for me, I rather write the whole code than lambda, until I understand this function.

And also this :roll_eyes: :grimacing:

Use nested loops to print the following output:

111111111
222222222
333333333
444444444
555555555
666666666
777777777
888888888
999999999

Tip: You can use the + operator to concatenate strings.

Extra tip
First, you will need a string variable where you will add characters to be printed on the current line.

If your outer loop uses a variable named i , then your inner loop should use range(0, 9) . In the inner loop, all you have to do is add the value of i to the string variable. You have to cast the integer i to a string first with: str(i) .

Finally, in the outer loop, after the inner loop finishes, print the string variable, and then set it to the empty string '' , clear it for reuse in the next iteration.

But it’s like reading a foreign language

@Lt.Smith Still a bit of a general problem, but I will give the first one a bash.

Solving problems with code is inherently a very logical process and the way you decide where to start writing is pretty much the same way you solve the problem otherwise. This is a typical procedural way of writing code, one of the main coding paradigms. So how does this work?

Say you want you are given a task to find all the even numbers in a large list of numbers. If you were to do this manually you probably follow the following procedure:

  1. Get your list of numbers
  2. Take the first number from the list of numbers
  3. Check if this number is a even number
    (a) If it is a even number, add it to my list of even numbers that I already have
    (b) If not, then just do nothing with the number
  4. Repeat these steps until you have checked all the numbers.
  5. Write out all the even numbers you found.

So where would you start if you had to do this programmatically? Well actually in exactly the same place.

1. Get your list of numbers
The numbers may in a csv file in which case you would need to first read it from file using any number of methods, using the pandas package popular for data analytics, or the normal python open command etc.

But for now lets just assume you have already done this and have an actual list of numbers s follows:

numbers = [3, 4, 5, 67, 445, 311, 764, 5678, 33345]

2. Take the first number of the list
This is easy. I have a list and to get to the first number I just need to do this numbers[0] and this will return 3. When I started coding this was very confusing to me. Why numbers[0] and not numbers[1] ? Python, like many other languages (but not all!) start numbering things at 0 and not 1. So numbers[0] represents the first element in the list numbers .

3. Check if this number is a even number
How do we check if it is even? Well there are many ways but let us go with the Modulus or Mod operator. What Mod does is it divides a number by another number and see if anything remains. Eg, 3 mod 2 = 1 but 4 mod 2 = 0. So when any number mod 2 = 0, it is even.

I can write a little function to this work for me in Python and it may look something like this:

def is_even(number):
    if number % 2 == 0:
         return True
    else:
        return False

(a better way to write this function would be

def is_even(number):
    return number % 2 == 0

which will provide the exact same result as the one above, but the first will work just fine.)

I send my number which is 3 to the function is_even by using the following code:

result = is_even(3)

The function checks if the modulus is equal (==) to 0 and if so returns True, if not it returns False.

So now I know if my first number is even or odd. I can create a new list to store this number in:

even_numbers = []
number = 3
if is_even(number):
    even_numbers.append(number)

Cool. My first number is checked and not added because it turns out to be uneven so my list remains empty.

But what about the rest then? So this is where the loops come in handy.

4. Repeat these steps until you have checked all the numbers.

I can write code to manually go through each component in the list but that is really no fun. Let’s rather use a for or a foreach loop for this.

Using the for loop is really easy and will look something like this:

for number in numbers:
    if is_even(number):
        even_numbers.append(number)

Here I cycle through every item in numbers, checks if it is_even and adds it to the even_number list if it is.

I can then print the even number list to make sure I got it right and it will give me:

[4, 764, 5678]

So to solve problems with code you follow the exact same procedure as you would without code. Break the problem into simple steps and then write code to do the work.

The full code for this example is here:

numbers = [1, 4, 5, 67, 445, 311, 764, 5678, 33345]


def is_even(number):
    return number % 2 == 0


even_numbers = []
for number in numbers:
    if is_even(number):
        even_numbers.append(number)

print(even_numbers)

There is an even more concise way to write this code and it looks like this:

numbers = [1, 4, 5, 67, 445, 311, 764, 5678, 33345]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

This uses a more advanced concept called List Comprehensions which Mosh also talks about. It is powerful but as with your problem with lambda functions, it is not important to make use of this right from the start. Do what works for you and what you understand.

Hope this helps.

1 Like

Thank you for explaining to me and for taking the time! Much appreciated!:smiley:
This I have to print in my memory : " *Break the problem into simple steps and then write code to do the work."
Your example code is not hard to understand, but this works better for me, seems much simpler :

numbers = [1, 4, 5, 67, 445, 311, 764, 5678, 33345]

new_numbers = []
for number in numbers:
if number % 2 == 0:
new_numbers.append(number)

print(new_numbers)

1 Like

Hi @Paul , here’s where I’m also having problems :grimacing:

sentence = “This is a common interview question”

dictionary = {}

for char in sentence:
if char in dictionary:
dictionary[char] += 1
else:
dictionary[char] = 1

print(dictionary)

I mean I understand the solution, but I don’t know how to put in code, meaning that I didn’t know to write this " dictionary[char] " to see if the char is or not in the dictionary, so that I have to increment it or not and I didn’t know that we have to use a dictionary to begin with

Plus the solution needs an update because from Python 3.7 dictionaries are ordered

@Lt.Smith Just a clarification on your comment that dictionaries are order in Python 3.7. they are not really ordered. The only thing that has changed is that they will keep the order in which items are added to the dictionary. This is different to being ordered and should not be confused.

1 Like

Thank you for the clarification!

@Lt.Smith A dictionary as well as a string are both a type of data structure that is known as an iterator. This means Python understands how to go from one element tot he next in an easy way. One of these easy ways is the for loop. So the following code:

for char in sentence:

is an easy way for you to tell Python you want it to do something with every element in sentence. starting from the first one all the way through to the last one. The elements of sentence are characters ('T', 'h', 'i'... ) . What you want to do in this case is count how many times a character appears in the sentence and to do this you first check if the character that Python has read from sentence already appears in your new dictionary. This what you do with the following statement:

if char in dictionary:

Apart from being an iterator a dict type is also a collection of some sort, or what Python calls, a mapping object. This means it maps one value (the key) to some other value (the value). To find out if a dict already contains a certain value as a key, you can simply ask: if char in dictionary:. This will make Python look at all the keys (not the values mapped to the keys) and see if there is a match. This is a very quick lookup for Python since each key is unique and easy to find.

You can do the same with any other collection. So lets say you have a list:

my_list = [9, 6, 5, 23]

you can also check if something is already in that list by writing for example if 9 in my_list:. This will also give you a True if it is or a False if it is not.

That is what you are doing with this call to if char in dictionary:. If Python finds the character char in dictionary it will return True otherwise it will return False.

So let us say that you are at the beginning of the for loop so you have not added anything to dictionary yet, so that means that if char in dictionary: will return False. So you must add a new entry to your dictionary. In Python we can do this by simply saying:

dictionary[char] = 1

What Python does is it creates a new entry in your dictionary variable with a key = T and a value = 1. If T already existed in your dictionary and you do this, it will simply replace the old value with (whatever it was) with 1. That is why you have the if statement. In other words, if dictionary[T] already exists, you should not make it equal to 1, but you should add 1 to the value that is already there. So that is why you call dictionary[char] += 1 (which by the way is a short way of writing dictionary[char] = dictionary[char] + 1 ). So here you add 1 to the existing value.

I hope this makes sense?

1 Like

It totally made sense! I will even read it again! Thank you again! Mosh should hire you!
I need to break down to pieces every problem and to take it step by step!

the interactions between you two are very helpful and educational @Lt.Smith and @Paul but I’m still confused on why Mosh assigned empty string to the command variable in the While loop lesson. What he wants is to mimic the interactive shell after you type python in the terminal or cmd
here’s the code:

command = “”
while command != “red”:
command = input(">")
print(“ECHO”, command)

Update about me: I enrolled at the Udemy Complete Python Beginner Bootcamp and it’s a slow process for me since I need to balance my part time job and learning Python but is this normal that whenever I try to practice for example what I learn from the while loops and for loops, it’s like I’m being repetitive? Like I’m just mimicking the examples I learned from there?

He assigned the variable command to the empty string because in the line below the variable ‘command’ is being compared to the word ‘red’. If you hadn’t assigned the variable ‘command’ before, what would have been compared the first time? Nothing? This will throw you an exception.
However, you can assign anything there - the value of this variable will be overwritten anyway → ‘command = input (’>’)’, right?
See for yourself:

command = 'you can write here whatever you want but this will only be printet once'
while command != 'red':
    print(command)
    command = input(">")
    print(command)

The first time the command variable is assigned to some string (it might be empty). Then the value is compared to the word “red”. The condition is not met, so we enter the loop. The first print statement will display the contents of the variable. Then input will overwrite the variable to the value you enter. Then the second print statement will display the new content.

If you type for example ‘blue’ the condition will not be met, so the loop will run again with the value ‘blue’. Result: ‘blue blue’

If you type ‘red’ only the second print statement is run, the value will be compared with ‘red’ = ‘red’ and the loop will terminate.

Have you tried Mosh’s Ultimate Javascript which starts with JS for beginners? Its a really good, gradual introduction to the concepts and covers for loops and more. Almost all programming languages have for loops - they are essential to reduce code and repeat instructions a number of times or iterate through a string, array, table etc. Each language has a different flavor of for loops but once you get it in one, you will be on your way in all. So, thats my recommendation. There are numerous things online, some good. Keep plugging away. You will get there and wonder why you ever had a problem! All the best.

Thank you Meski! Your explanation really helped me a lot!

Would it be a good thing to jump into another programming language? I am enrolled in Udemy’s Python for Beginners and often times I ask myself if this is the right path because I am so confused on how things work etc but I really want to learn programming and hopefully find a job in relation to Python

If python is what you want to work at then stick to that. Look for other resources online. post questions on here, stackoverflow. There are tons of resources. Once you get the hang of the concepts, variables, objects, arrays, functions, operators, control flow - if else / case, loops (for, while) what you learn in python will make learning another language easier. Ive done Mosh’s python course and looked at a couple of others on youtube.
The fact you mentioned the “right path” means you are already thinking right. There are many choices out there, many people telling you do this, dont do that. I say, do what interests you and learn how you like to learn. For me, I like books. I like courses that take you through “real-world” examples. Id like to see an advanced python course from Mosh. For python, I suggest doing a few of the python starter app videos on youtube. Think of some things you want to do and try and dont worry if you dont get it to start with. None of us are born programmers. All the best!

1 Like