Day 2: Random Exercises

  1. This was more of a find around the library part.
# Write a Python program to get the Python version you are using.
# Write a Python program to display the current date and time.

import datetime
import sys



2. Fiddling around with another library

# Write a Python program which accepts the radius of a circle from the user and compute the area.

import math

radius = int(input("Enter the radius of the circle: "))
area1 = math.pi * pow(radius, 2)
area2 = math.pi * radius**2

So in this as we see, there are two ways in which we can print the area:

  • Using math library, we can use the power function and pass on the value of our radius and the power to which it has to be raised.
  • Other is explicitly calling the exponential function using double asterisk.


3. This was more of a slicing function

# Write a Python program which accepts the user's first and last name
# and print them in reverse order with a space between them.

name = input("Enter your name please: ")
if len(name) > 0:

Slicing is a way in which we can split our set of string/number/lists and display certain set of characters from it.



Day 1: Sample String Output

# Write a Python program to print the following string in a specific format (see the output).
# Sample String : "Twinkle, twinkle, little star,
# How I wonder what you are! Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twinkle, twinkle, little star,
#  How I wonder what you are!
#     Up above the world so high,
#     Like a diamond in the sky.
# Twinkle, twinkle, little star,
#  How I wonder what you are

sampletext = """Twinkle, twinkle, little star,
How I wonder what you are! Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star, How I wonder what you are"""

newsample = """Twinkle, twinkle, little star,
\n \t How I wonder what you are! 
\n \t \t Up above the world so high,
\n \t \t Like a diamond in the sky.
\n Twinkle, twinkle, little star,
\n \t How I wonder what you are"""


So lets start with the basics:

  1. # (aka hashtag) is used to comment a line.
  2. Single line strings are stored in either single quotes (‘…’) or double quotes (“…”).
  3. Multiple line strings are stored in triple quotes (“””…”””) or 3 single quotes.
  4. \n – Escape sequence used to add a new line.
  5. \t – Escape sequence used to add tab (space) before the text. Tab generally ends up adding 4 spaces before start of the string.

So the trick was very simple here. Using escape sequence, you can simply display your text in the manner asked.


  1. Using hash tag for multiple lines is not possible like what we did for multi line string. Hash tag needs to be added on each line.
  2. I’m using Pycharm by JetBrains. It is very similar to Visual Studio or any other heavy text editors. I googled a lot and ended up for this since I had previous experience with VS and I found it easy to have my words print before me even before I complete them. #lazyassproblems
  3. I think its a beautiful app though. 🙂

New Approach Rules

  1. Write a program without feeling embarrassed even if it’s a simple print statement.
  2. Its okay to struggle. Accept it and learn and study more. Look for related articles which have simplified versions of it.
  3. If that is still not clear, talk to people who know about it.
  4. Solve the problem on your own. Without looking into the solution beforehand.
  5.  Struggle is real bruh. But its worth it. 😀

Website: Python Exercises

Or maybe you are just doing it wrong!

So yes, I have been lagging behind. A lot. I presumed that if I jumped right into practicing, I’ll understand the concepts.

To some extent, I did. But that extent was limited to certain time period and then poof! Gone. My memory has more RAM than ROM. *tch tch such a poor technical joke* But yes. I remember silly details but I forgot the important ones. Just like chrome. *tch tch. Another sad joke*

And after struggling for 10 days on a super simple silly question, and while giving a sincere advice to a friend who was fretting over her speed as well, I realized how much basics and practice we need before we do jump into the real world.

So the point is, if your basics are not clear, nothing will ever be clear to you. Whatever you would be doing will just represent the work of just another developer – NOT A GOOD DEV. My concepts were still not clear and I tried really hard to get into Python’s intermediate side more earlier than required. I was still struggling to figure out what simple modules did. How to use some libraries etc. Epic Fail. Waste of time. Waste of energy because I’m again starting from scratch when I could have easily been on the good side of python by now.

You know, trying to jump all over, trying and assuming you can literally grasp anything and everything in few months and being at the same level of a 5 yr old developer in the same field is a huge huge misconception. Until of course you are a robot for which you would have been programmed to do it by now and then if it takes you 10 days to figure out a 50 line of code program, then you are a lull.

While talking to an acquaintance on one of my communities of slack, I was narrating him the sad story of my struggle over the cows and bulls game, he just simply made one statement – You must be doing it wrong.

Yes! Of Course. I was doing it wrong. In spite of knowing what I had to do, I still couldn’t figure out the correct way to get it done. Why? Because I was in a rush to finish it off instead of pulling it off.

So here I am, again – trying to re-learn whatever I had learned till now, again from scratch, with the basics and more practice on each and every step, not trying to jump out of something. Its hard. Like really really hard. Especially when you had high hopes with yourself. But its okay to dust off your failures, learn and move on. *tch tch. reading too much self helps I guess* Its nothing to feel embarrassed about. Take as much help as needed. Its okay! Its all okay. And everything will get okay. Learn to accept your pace and just focus on improving yourself for yourself and not others. *happy tears* *facepalms for reading too much self help and positive things*

10 Days Later..: Cows & Bulls

# Create a program that will play the “cows and bulls” game with the user.
# Randomly generate 4 digit number.

import random

complist = '123456789'
compnum = random.sample(complist, 4)
compnum = list(map(int, compnum))  # To convert string array to int array since above makes a string list
# print(compnum)  # This shows your final output

def userinput():

    userinp = input("Please enter a 4 digit number: ")
    if len(userinp) < 4 or len(userinp) > 4:
        print("The value should be <> 4")
        userinp = [int(i) for i in str(userinp)]  # This converts the number to a list format
        checkdigits(userinp, compnum)

def checkdigits(userinp, compnum):

    bull_count = 0
    cow_count = 0

    for i in range(0, len(compnum)):
        if compnum[i] == userinp[i]:
            bull_count += 1

        for j in range(0, len(userinp)):
            if compnum[i] == userinp[j] and i != j:
                cow_count += 1
    if bull_count == 4:
        print("Congrats! Correct guess!")
    elif cow_count >= 0 or bull_count >= 0:
        print("You have " + str(cow_count) + " cows and " + str(bull_count) + " bulls! Try again..? Y/N")
        tryagain = input()
        if tryagain.lower() == 'y':



I had a really really hard time figuring this one out. Honestly. There was a point where I just wanted to give up and mostly because I’m not well versed with lists. I was not aware that you could simple “array-fy” it and compare index values present in the list.

Day 16: Show all the headlines from NY Times using BeautifulSoup & Requests packages

So, I didn’t use requests package. I did download it, tried somethings with it, but it didn’t help and I didn’t get it.

Although I did find an alternative to it – urllib (since I’m on Python 3.6).

# Use the BeautifulSoup and requests Python packages
# to print out a list of all the article titles
# on the New York Times homepage.

import string
from bs4 import BeautifulSoup
from urllib.request import urlopen

testurl = ''
soup = BeautifulSoup(urlopen(testurl), 'lxml')
newheadings = soup.find_all(class_="story-heading").__str__()
test = str.strip(newheadings, '</a>')

I’ll try it out using requests library.

Lessons Learned:

  1. New libraries – BeautifulSoup, Requests, urllib
  2. BeautifulSoup and Requests are external libraries which needs be installed using pip/easy_install.
  3. Conversion of ResultSet to String which is done by this LOC:


  4. Using strip – which is used to strip of characters or blank spaces before or after (check this link) – does not work for me. Need to seriously figure this out.
  5. Copy-pasting your own running code, ends up not working. Re-write the whole thing which clear head as to what you want. Since I’m still learning and still get to know a lot of things, but by knowing what you want your code to do will make it easy. [Enough philosophy!]
  6. NY Times has a very shabby page though. No offence though to the designers as well.
  7. This was tough. Seriously.
  8. Prettify – Shows your page in an XML format which is pretty cool.
  9. Oh and here’s the link to see the difference. Sorry. I really need to study more.

Day 15: Generate Random Password

# Write a password generator in Python.
# strong passwords have a mix of lowercase letters, 
# uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password 
# every time the user asks for a new password.
# Include your run-time code in a main method.

import string
import random

characters = string.ascii_letters
chartest = [characters[i] for i in range(len(characters))]
digits = string.digits
special = string.punctuation
randomValue = characters + digits + special

def createpassword(randomValue, passlen):
    password = ''.join(random.sample(randomValue, passlen))
    return password

def mainstart():
    passlen = int(input("Enter the length of your password greater than 6: "))
    if passlen < 6:
        print("Password should be greater than 6. Retry!")
        password = createpassword(randomValue, passlen)
        reqagain = input("Want to try again? Y/N ").lower()
        if reqagain == 'y':


Day 14: Listing with String Part 2

# Write a program that asks the user for 
# a long string containing multiple words.
# Print back to the user the same string, 
# with the words in backwards order.

def inputstring():
    testing = input("Enter a string: ")
    a = len(testing)
    printwordsback(a, testing)

def printwordsback(a, testing):
    if a > 1:
        set2 = [testing[i] for i in range(len(testing))]
        for i in range(len(set2)):
            set1 = set2[::-1]
            print(' '.join(set1))


Lessons Learned:

  1. How to split the string into individual characters.

Day 14: Listing with Strings Part 1

# Write a program that asks the user for a long string containing 
# multiple words.
# Print back to the user the same string, 
# except with the words in backwards order.

def inputstring():
    testing = input("Enter a string: ")
    a = len(testing)
    printwordsback(a, testing)

def printwordsback(a, testing):
    if a > 1:
        listing = testing.split()
        for i in range(a + 1):
            set1 = listing[::-1]
            print(' '.join(set1))


Lessons Learned:

  1. Converting a list to string can be done by join. Giving space between the single quotes adds space between the texts.
  2. If you want to print all the characters in reverse order, [: : -1 ] is to be used.

Day 13: Listing again!


# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.

import random

def mainstart():
    testing = int(input("Enter the length of the array: "))

def input_array(testing):
    a = [random.randint(0, 100) for i in range(testing)]
    print("Array: "  + str(a))
    # take_array(a)
    printfirstandlast(testing, a)

def printfirstandlast(testing, a):
    c = []
    for i in range(testing):
        b = a[0]
        b = a[-1]



Lessons Learned:

  1. I need to start practicing regularly. I’m forgetting what I’m learning.
  2. If you slice a list and append it, then list of list will be formed and not a simple one. [[num1], [num2]] – Wrong
    Instead [num1, num2] – Correct
  3. I was getting continuous error on runtime when I tried running the code only to realise that my last function printfirstandlast I was passing the incorrect variable. So in short when I had to pass two variables, I was only passing one (only the array) and even in my range function I had passed the incorrect variable (the array instead of the length).