# Easy Solutions To CodeAcademy Python Challenges For Beginners – Round 1 of #LearnPythonFromScratch

In my opinion, the most challenging thing about learning Python is not the lack of learning resources. In fact, you could learn Python from Code Academy, Coursera, Udemy, W3Schools, Learn Python, and Data Camp. It took me about 50 hours of tutorials and practice to understand the language’s basic syntax and fundamentals.

The real challenge is to find suitable exercises that test your understanding of the language and lead you toward the next stage of the learning process. For me, these exercises are an essential way of escaping the “tutorial hell” where you get stuck typing code displayed on the screen.

In this first round of testing my Python skills, I decided to go through the 10 Python Code Challenges for Beginners. I gave myself 21 hours (3 hours a day for a week) to code all ten challenges. At the end of the 21 hours, I was through nine challenges.

**But Before I Discuss The Challenges …**

I want to mention that the code is not optimized for performance or conciseness. At this point, I’m a beginner trying to get the desired output without copying code snippets.

With that out of the way, let’s start.

- Challenge # 1: Convert Radians into Degrees
- Challenge # 2: Sort A List
- Challenge # 3: Convert A Decimal Number Into Binary
- Challenge # 4: Count The Vowels In A String
- Challenge # 5: Hide The Credit Card Number
- Challenge # 6: Are the Xs equal to the Os?
- Challenge # 7: Create A Calculator Function
- Challenge # 8: Give Me The Discount
- Challenge # 9: Just the Numbers
- Challenge # 10: Repeat the Characters
- That's A Wrap!!

Challenge # 1: Convert Radians into Degrees

From the official prompt:

*Write a function in Python that accepts one numeric parameter. This parameter will be the measure of an angle in radians. The function should convert the radians into degrees and then return that value.*

I used this result to test the code: **9.22 rad** = **528.2671 degrees**.

The first challenge looks easy- convert radians into degrees. It’s a simple formula that involves simple arithmetics.

The first problem I faced was the value of PI. I started with the traditional value of 3.14 but soon realized I needed to go to several decimal places to get accuracy. After messing around with the decimal places, I took the shorter route and used the constant PI included in the math package.

The rest of the code is straightforward. The main() function gets the value in radians from the user and passes it to the to_degree() function. This function converts radians to degrees and returns the value.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 1
#Write a function in Python that accepts the measure of an angle in radians.
#The function should convert the radians into degrees and then return that value.
#to_degree() takes the input from main() as the floating point measure of angle in radians.
#It applies the standard conversion to degree formula and returns the answer rounded off to four decimal places
#To keep things simple, it uses the value of PI defined in the standard MATH library.
#key: 9.22 rad = 528.2671 degrees
#Import the standard MATH library
import math
#to_degree() takes the input from main() as the floating point measure of angle in radians.
#It applies the standard conversion to degree formula and returns the answer rounded off to four decimal places
#To keep things simple, it uses the value of PI defined in the standard MATH library.
#key: 9.22 rad = 528.2671 degrees
def to_degree(rad):
x= (rad*180/math.pi)
y=round(x,4)
return(y)
#main()
print("This Program converts measure of an angle in radians to degrees")
rad = float(input("Enter measure of the angle in radians > "))
#Accepts value from toDegree() and print the answer
x=to_degree(rad)
print(str(rad) + " radians is " + str(x) +" degrees")
```

## Challenge # 2: Sort A List

Here’s the official prompt:

*Create a function in Python that accepts two parameters. The first will be a list of numbers. The second parameter will be a string that can be one of the following values: asc, desc, and none.*

The second challenge has a lengthy problem statement and can intimidate first-timers. Instead of just a simple sort, the problem statement mentions three scenarios, including where the list would be printed as is.

The main() function takes the list of numbers and the sorting parameter. It then passes them to the sortt() function that calls the appropriate method. Python provides a very convenient sort() method that sorts a list in both ascending and descending order.

While you might think that sorting is the tough part of this challenge, that’s not so. My roadblock came at the list input part of the main() function. The input() function I used to get the list of numbers from the user generates a string. I needed to split the string into individual elements and convert each into an integer. After a couple of false starts, I decided to use the map() function that iterates a function for all the members of the list.

The sortt() function was actually the easy part with the nested if – elif structure that called the appropriate method for the second parameter (asc, desc, none). Sorting the numbers in ascending order is easy with the sort() method. Similarly, I used the reverse = True argument for sorting the numbers in descending order.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 2
#Write a function in Python that accepts two parameters.
#The first will be a list of numbers.
#The second parameter will be a string that can be one of the following values: asc, desc, and none.
#The function should return the list sorted or as is, depending upon the second parameter.
#sortt() takes two parameters. The first is the list of numbers, and the second is the sort request. It returns the list depending upon the value of the second parameter
def sortt(lst,par):
if par == "asc":
lst.sort()
print(*lst)
elif par == "desc":
lst.sort(reverse = True)
print(*lst)
elif par == "none":
for z in range(len(lst)):
print(*lst)
#main()
print("This program takes a list of numbers and a parameter for sorting the list")
#Get input in the array and remove whitespaces
l = list(map(int, input("Enter numbers > ").split()))
# Get the second parameter
p = input(" How would you like to sort this list? > ")
sortt(l,p)
```

## Challenge # 3: Convert A Decimal Number Into Binary

The following is from the official prompt:

*Write a function in Python that accepts a decimal number and returns the equivalent binary number.*

Converting the base of a number is a common enough challenge that tests how well you can translate a well-understood algorithm into code that produces the desired output.

I converted 13 into binary on paper to recall the process and to list down the steps. These steps were converted into the to_bin() function that converts the decimal number received from the main() function. As you can see in the to_bin() function, I implemented the standard division-quotient method of converting from decimal to binary. Unfortunately, it took me two tries to get the code working because I forgot to convert the decimal number into an int, resulting in the error.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 3
#Write a function in Python that accepts a decimal number and returns the equivalent binary number.
def to_bin(d):
arr=[]
dec=d
while dec >= 1:
rem=int(dec/2)
que=int(dec%2)
arr.insert(0,que)
dec=rem
print(*arr)
#main()
print("This program converts a decimanl number into its binary counterpart")
d = int(input("Enter the decimal number > "))
to_bin(d)
```

## Challenge # 4: Count The Vowels In A String

*Create a function in Python that accepts a single word and returns the number of vowels in that word.*

This challenge looks simple because of the simple problem and easy solution – get the word from the user and then count the instances of vowels (a,e, i,o,u).

The trick in the count_vowel is to compare the elements of the test string to a list of vowels. Every time there’s a match, a counter is incremented. The function returns the counter, and the main() function prints this value in a string.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 4
#Create a function in Python that accepts a single word and returns the number of vowels in that word.
#countVowel() gets a list from main() and counts vowels
def count_vowel(w):
counter =0
for x in w:
if x in ['a', 'e', 'i', 'o', 'u']:
counter=counter+1
print("The string has " + str(counter) + " vowel(s)")
#main()
print("This program counts the number of vowels in a string")
wd = input("Enter the Word > ")
count_vowel(wd)
```

## Challenge # 5: Hide The Credit Card Number

*Write a function in Python that accepts a credit card number. It should return a string where all the characters are hidden with an asterisk except the last four.*

This is an interesting challenge that builds a very familiar-looking utility.

Getting the output right took some effort. I started by researching the length of credit card numbers. I found that these numerical strings can have 13, 15, or 16 characters. This check was added to the main() function. Once the string passed this test, it was passed to the hide_CC_number() function. This function retains the last four digits of the string and substitutes * for the rest.

After several tries of directly handling the string, I decided to set up an empty list and use the append() list method to add the * and the last four digits. The function substitutes an * for the numbers until the last four digits. Next, the function adds the numbers to the list for these four numbers. The function then prints the array.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 5
#Create a function in Python that accepts a credit card number.
#It should return a string where all the characters are hidden with an asterisk except the last four
#hideCCNumber() takes the card number from main() and formats it with * and display the last four numbers.
#hideCCNum()
def hide_CC_Number(ccnumb):
arr=[]
#x=0
length = len(ccnumb)
for x in range(length-3):
arr.append("*")
while x != length:
arr.append(ccnumb[x])
x=x+1
print(*arr)
#main()
print("This program takes a Credit Card Number (without dashes or spaces) and hide it, except the last four numbers")
#get number
ccnum = input("Enter the number> ")
#check length (13 15 16)
if len(ccnum) == 13 or len(ccnum) == 15 or len(ccnum) == 16:
hide_CC_Number(ccnum)
else:
print("incorrect card number!")
```

## Challenge # 6: Are the Xs equal to the Os?

This interesting challenge asks you to write a function that counts the instances of Xs and Os and mentions which is higher.

The logic of the function checkXO() is pretty easy – start counting the instances of Xs and Os. I set up two variables countx and counto as counters. Then, the function receives the string from main() and starts testing the string for Xs and Os. After writing the first version of checkXO(), I realized that the user could enter Xs and Os in either case.

I rewrote the function to check for both cases and was satisfied with the results. The function then prints the frequency of Xs and Os. I was feeling pretty good about myself when I reread the challenge description. The expected outcome was comparing the instances of Xs and Os and mentioning which character has a higher number.

I rewrote the function to accommodate this requirement, and the new version turned out to be great.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 6
#Create a function in Python that count the number of Xs and the number of Os in the string.
#If the count of Xs and Os are equal, then the function should return True. If the count isn’t the same, it should return False.
#If there are no Xs or Os in the string, it should also return True because 0 equals 0. The string can contain any type and number of characters.
#checkXO() takes a string and counts the instances of Xs and Os. It then returns the appropriate response
def checkXO(w):
countx=0
counto=0
for x in range(len(w)):
if w[x] == "x" or w[x] =="X":
countx=countx+1
elif w[x] == "o"or w[x] =="O":
counto=counto+1
print("there are " + str(counto) + " Os and " + str(countx) + " Xs in the string " + str(w))
if countx > counto:
print("There are more Xs than Os")
elif countx < counto:
print("There are more Os than Xs")
else:
print(" The Xs and Os are equal")
#main()
w = input("Enter the string > ")
checkXO(w)
```

## Challenge # 7: Create A Calculator Function

I skipped this challenge because it is cliche. I had written the function before and didn’t feel like repeating it.

So on to Challenge # 8.

## Challenge # 8: Give Me The Discount

I feel like this challenge was put at number 8 to encourage the coders to finish the ten challenges. It was pretty easy and involved deducting a percentage from the total amount.

The function apply_discount() receives two arguments, the total price and the discount percentage from the main() function. It then calculates the price after applying the discount percentage.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 8
#Create a function in Python that accepts two parameters.
#The first should be the full price of an item as an integer.
#The second should be the discount percentage as an integer.
#The function should return the price of the item after the discount has been applied.
#For example, if the price is 100 and the discount is 20, the function should return 80.
#apply_discount() takes two int parameters, and returns the discounted price.
def apply_discount(price,discount):
dicounted = price -(price*(discount/100))
return(dicounted)
#main()
print("This program calculates the discounted price")
price = int(input("Enter the full price> "))
discount = int(input("What's the discount percentage? "))
ans = apply_discount(price,discount)
print(str(ans))
```

## Challenge # 9: Just the Numbers

This is one of those challenges with a simple prompt – get an alphanumeric string from the user and print out just the numbers as they occur in the original string.

I sketched out the logic and then started writing the code. The main() function is pretty simple because it just prints the introduction and then gets the input from the user. It then passes it to just_numbers(), where the processing happens.

While reading the logic, I realized that it is easy to write (“if x is NUMBER, push it to list”), but translating it in an actual Python condition is another story.

After a couple of wrong turns, I decided to explore the built-in list methods because I was pretty sure somebody way more intelligent than me must’ve cracked this problem a long time ago. Finally, my hunch paid off, and I found the isalpha() method.

After that, it was straightforward to use an if: statement to separate out the numbers (by checking that isalpha() returns False) and append them to a list. Once the for loop finishes, the list containing the numbers is printed.

Here’s my solution:

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 9
#Create a function in Python that accepts a list of any length that contains a mix of non-negative integers and strings.
#The unction should return a list with only the integers in the original list in the same order.
#just_numbers() takes the list from main() and returns just the numbers in the order of appearance in the original list.
def just_numbers(s):
arr=[]
for x in range (len(s)):
if s[x].isalpha() == False:
arr.append(s[x])
print(*arr)
#main()
print("This program strips the non-numaric portion of a string and returns just the numbers in original order")
s = input("Enter the string > ")
just_numbers(s)
```

## Challenge # 10: Repeat the Characters

This is another challenge that looked easy but gave me a tough time. So here’s the official prompt:

Create a Python function that accepts a string. The function should return a string, with each character in the original string doubled. For instance, an input of 123a! should return 112233aa!!

Easy enough, right?

Not so.

Since these challenges are aimed at beginners, I decided not to use any fancy Pythonese.

I tried a lot of list comprehension tactics, but either was unable to double the characters or the final output had spaces in between the characters. Finally, after nearly an hour, I decided to call it a day and entered the solution I wrote in the comments.

You’ll most definitely find a much more elegant solution for this challenge, but my hour-long window was up. The function double_char() simply adds the character twice (two separate calls) in the target list. Finally, it prints the list.

Here’s my solution

```
#CodeAcademy Python Challenges for Beginners
#https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/
#Challenge 10
#Create a function in Python that returns a string, with each character in the original string doubled.
#key: 123a! returns 112233aa!!
#double_char takes the string from main() and returns a string with each character in the input string doubled.
def double_char(strng):
arr=[]
for x in range (len(strng)):
arr.append(strng[x])
arr.append(strng[x])
print(*arr)
# return ''.join([char*2 for char in strng])
#main()
print("This program doubles the characters in a string")
string = input("Enter string > ")
outputString = double_char(string)
#print(string)
print(outputString)
```

## That’s A Wrap!!

This blog covers the Ten Python Challenges For Beginners by Code Academy. I solved nine out of ten challenges and presented my code. I am sure the solutions would help other budding Python coders understand and apply basic Python syntax.

I’ll come back with detailed coverage of Pandas, the popular data manipulation library.

Until then!!