Python Practice: Beginner 1

Python Practice: Beginner 1

12/6/2017


Introduction

I am a firm believer that to learn a progamming language well, you need to practice by doing hands on exercises and building real projects as much as possible. Reading books is a great help, but until you start doing hands on exercises, your practical skill in the language won't progress. That's why I'm starting a new blog series focused on python exercises and project ideas.


Each one of these posts will consist of 3 to 5 practice problems, each of which get harder as the problems go along. Each problem will contain 4, possibly 5 different sections.

  1. Problem Statement. This will be a description of the program. You write code to solve this problem.
  2. Techniques Practiced. This shows all of the different techniques I used in my solution, and ones that I think most people will use in theirs as well. This is partially a hint, and partially just awareness for you to seek out things you need practice with.
  3. Sample Output. This will be the output from me running the solution on my computer. You should write your code to output in a similar manner to the example.
  4. Solution. Each problem will contain a solution I wrote. Please don't think this is the only solution. There are many ways to solve problems and programming is no different. I'll include two solutions sometimes when there's two distinct ways I think people will solve the problem. The solutions will be hidden by default to encourage you to solve it on your own without viewing the solution.
  5. Starter Code. A few examples will require starter code to make things a bit easier. Most won't have this because I think half the battle is getting started.
Let's get started!


1) Print odd numbers

Problem Statement

Write a program to print all odd numbers between 1 and 50.

Techniques Practiced

for loops


Sample Output

1
3
5
7
...
45
47
49

Solution

# Most common way
for i in range(1, 50):
    if (i % 2 != 0):
        print(i)

# Simpler way
for i in range(1, 50, 2):
    print(i)
      


2) Beat the dealer

Problem Statement

Write a program simulating a game of beat the dealer. Here how it's played: the player and the dealer each roll two standard die. If the player's roll is higher, they win. Otherwise, the dealer wins. Hint: you will need to use the random library.

Techniques Practiced

conditional logic libraries


Sample Output

The player rolled a 10.
The dealer rolled a 4.
The player won!

Solution

import random


player_roll = random.randint(1, 6) + random.randint(1, 6)
dealer_roll = random.randint(1, 6) + random.randint(1, 6)

print("The player rolled a {}.".format(player_roll))
print("The dealer rolled a {}.".format(dealer_roll))

if player_roll > dealer_roll:
    print("The player won!")
else:
    print("The dealer won!")
      


3) Replace Vowels

Problem Statement

Write a program to replace all vowels in the given string with underscores. Print out the replaced string when complete.

Techniques Practiced

built-in python functions for loops


Sample Output

Th_s _s _ t_st str_ng!

Starter Code

string_to_replace = "This is a test string!"
vowels = ['a', 'e', 'i', 'o', 'u']

Solution

string_to_replace = "This is a test string!"
vowels = ['a', 'e', 'i', 'o', 'u']

for vowel in vowels:
    string_to_replace = string_to_replace.replace(vowel, "_")

print(string_to_replace)
      


4) Guess the number

Problem Statement

Write a program that generates a random number between 1 and 100. Get input from the user to try to guess the number. Let the user know if they are over or under. Keep track of the number of guesses the user takes. Once the user guesses correctly, let them know how many guesses it took.

Techniques Practiced

user input type casting while loops counters


Sample Output

Please guess a number between 1 and 100: 50
You guessed too low!
Please try again: 75
You guessed too low!
Please try again: 90
You guessed too high!
Please try again: 85
You guessed too high!
Please try again: 80
You guessed too low!
Please try again: 83
You guessed too high!
Please try again: 82
You guessed too high!
Please try again: 81
You guessed it right! The number was 81
You guessed 8 times


Solution

import random


player_guess = int(input("Please guess a number between 1 and 100: "))
random_num = random.randint(1, 100)
guess_counter = 1

while player_guess != random_num:
    if player_guess > random_num:
        print("You guessed too high!")
    else:
        print("You guessed too low!")

    player_guess = int(input("Please try again: "))
    guess_counter += 1

print("You guessed it right! The number was {}".format(random_num))
print("You guessed {} times".format(guess_counter))
      


5) Write user input to file

Problem Statement

Write a program that takes user input and writes it to a file on your local file system. Let the user input as many times as they want, until they say they're done. Once they're done, write everything they've said so far to a file on your computer with a line seperating each input. Name the file "user_output_" with a timestamp on the end so they are unique.

Techniques Practiced

user input while loops conditional logic files arrays libraries


Sample Output

What would you like to say: I send you this cadmium red
Are you finished writing? Please type yes or no. no

What would you like to say: One for every layer I shed
Are you finished writing? Please type yes or no. no

What would you like to say: And I shed one layer for this
Are you finished writing? Please type yes or no. yes



Solution

import time


user_finished = False
user_input_collection = []

while not user_finished:
    user_input = input("What would you like to say: ")
    user_input_collection.append(user_input)

    user_finished_input = input("Are you finished writing? Please type yes or no. ")

    if user_finished_input == "yes":
        user_finished = True

filename = "user_output_{}".format(time.time())
output_file = open(filename, "w")

for entry in user_input_collection:
    output_file.write(entry + "\n")

output_file.close()

      
$ cat user_output_1512608563.5720553
I send you this cadmium red
One for every layer I shed
And I shed one layer for this


I hope you enjoyed these 5 practice problems. One thing I'd like to mention is that none of these examples with user input validated the input. If you want to add on to these, validate the user's input and if they input isn't valid, request for it again.

Let me know if you thought these were too easy or too hard for a beginner. I hope to have some more practice problems out in the next few weeks!


Check out more posts in the Python category!