{{announcement.body}}
{{announcement.title}}

A Better Way to Learn Python

DZone 's Guide to

A Better Way to Learn Python

In this article, take a look at some courses to learn Python as well as a few example programs.

· Web Dev Zone ·
Free Resource












Python is just the language for you. The smart way to learn Python is by practicing more programs in Python. In this series, we are going to write more and more programs to get clarity over a concept. At the end of the series, we will be ready for production quality code experience and we will try to cover most aspects of the readiness.

This is part 1 of the series, where we will focus on how to start and learn the basics or fundamentals of Python. All the courses that we will discuss are free and are some of the best course to learn and digest Python easily. Practice as much as you can and follow the steps like writing code, failing, analyzing, fixing it, writing it again, and so on. So by practicing writing more pythonic code, we will learn more and get a hands-on experience for developing production-ready code.

Warning: These are not the best performant programs. There may be better than these. 

FAIL FAST

In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. [wiki]

" In theory, theory and practice are the same. In practice, they are not. " Dr. Albert Einstein

Let's see where to start, what IDE to use, where to learn and learn for free.

We are not going to repeat the fundamentals; you can read it yourself. There are plenty of blogs and tutorials available for learning Python. In this series, we will write a few programs to prove that the concepts work.

After learning the first few sessions of Python and becoming comfortable with the programming construct, let's jump to a few programs (in no specific order).

✅P001 

Return number of days in a month where the year and month is given.

Here we are also checking if the given year is a leap year or not. 

You will note we are using list, if condition, function, comments, and a few operators of Python.

Python
 





x
23


 
1
# Leap year test 
2
# https://github.com/simplymanas/python-learning/blob/master/LeapYear.py
3
 
          
4
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
5
 
          
6
def is_leap(year):
7
    """True if leap year, False if non-leap year """
8
 
          
9
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
10
 
          
11
 
          
12
def days_in_month(year, month) -> object:
13
    """no of days in that month"""
14
    
15
    if not 1 <= month <= 12:
16
        return "Invalid month"
17
 
          
18
    if month == 2 and is_leap(year):
19
        return 29
20
 
          
21
    return month_days[month]
22
 
          
23
print (days_in_month(2020, 2))



✅P002 

How many times a letter is repeated in a given string.

We are using a library and have imported it (https://docs.python.org/3.8/library/collections.html)

A Counter is a dict subclass for counting hashable objects. (From https://docs.python.org/2/library/collections.html)

Python
 





xxxxxxxxxx
1


 
1
# find out how many times a letter is repeated in a sentence
2
from collections import Counter
3
mouse = Counter("Manually Operated Utility Selection Equipment")
4
print(mouse)
5
 
          
6
# output
7
# Counter({'e': 5, 't': 5, 'l': 4, ' ': 4, 'i': 4, 'a': 3, 'n': 3, 'u': 2, 'y': 2, 'p': 2, 'M': 1,
8
# 'O': 1, 'r': 1, 'd': 1, 'U': 1, 'S': 1, 'c': 1, 'o': 1, 'E': 1, 'q': 1, 'm': 1})



✅P003

Prime number test. We are using the for loop here and the catch is there is one else statement in python for loop as well. 

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs (From https://docs.python.org/3/tutorial/controlflow.html)

Python
 





xxxxxxxxxx
1


 
1
# Prime number test
2
for n in range(2, 8):
3
    for x in range(2, n):
4
        if n % x == 0:
5
            print (n, ' = ', x, '*', n // x, ', hence', n, 'is not prime')
6
            break
7
    else:
8
        # no factor found
9
        print (n, 'is a prime number')



✅P004

Remember in school, the teacher used to ask us to write a line 10 times. The perfect solution is here. You can also use the range keyword to achieve this; try that at home (no risk).

Python
 





xxxxxxxxxx
1


 
1
# repetitive sequence.
2
print('If you make mistake , write it 10 times :) ')
3
repeated_string_sequence = 'Python ' * 10
4
print(repeated_string_sequence)
5
 
          
6
# now this is a list
7
repeated_item_in_a_list = ['Powerful'] * 10
8
print(repeated_item_in_a_list)



✅P005

List comprehension

It is more like a power pack in a single line of python and a better and concise way to use a list. Sometimes it is less efficient and harder to read, so use it when you think you are better at this.

For your homework - Is this better at readability than a lambda? 

Python
 





xxxxxxxxxx
1
25


 
1
# list comprehension
2
vegetables = [
3
    {'name': 'Potato', 'price': 40},
4
    {'name': 'Tomato', 'price': 20},
5
    {'name': 'Onion', 'price': 25},
6
    {'name': 'Pumpkin', 'price': 45}
7
]
8
 
          
9
# Regular way
10
vegetable_names = []
11
 
          
12
for vegetable in vegetables:
13
    vegetable_names.append(vegetable['name'])
14
 
          
15
print(vegetable_names)  # ['Potato', 'Tomato', 'Onion', 'Pumpkin']
16
 
          
17
# list comprehension
18
print([vegetable['name'] for vegetable in vegetables])  # ['Potato', 'Tomato', 'Onion', 'Pumpkin']
19
 
          
20
# adding a condition
21
print([vegetable['name'] for vegetable in vegetables if vegetable['name'][0] == 'P'])['Potato', 'Pumpkin']
22
 
          
23
# ['Potato', 'Pumpkin']
24
 
          
25
# this applies to dictionary as well



In the next part, we will write more programs and explore more features of Python. Once you read a concept here, go back and learn it from the resources and write a program of your own and check in to your git. You are done for the day: add a point for yourself, a diamond point

References

https://github.com/simplymanas/python-learning

https://www.freecodecamp.org/learn

https://www.python.org/

A Few More Challenges

https://pythonprinciples.com/challenges/

Keep smiling and keep learning.


Topics:
ai artificial intelligence, code, learn python, python, python courses, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}