Replace all instances of a character or word with another; Python Programming

replace

 

In the first instance we are going to replace all instances of a British Pound sign in a given sentence with that of a dollar sign. Thankfully Python has this covered, making it simple little program.

First we create our variable Sentence and assign it with input from our user.

 

Sentence = input(“Please enter a sentence:”)

 

Then we use the .replace() method to do the work for us.

We give it two arguments; the symbol we want to replace followed by what we want it replaced with. In this case its replace all instances of £ with $

We assign the results to a new variable with the very same name; Sentence

 

Sentence = Sentence.replace(‘£’,’$’)   #don’t forget the comma

 

Now all that is left is to print the variable Sentence to the screen

print(Sentence)

 

The full program:

Sentence = input(“Please enter a sentence:”)

Sentence = Sentence.replace(‘£’,’$’)

print(Sentence)

 

We could of course use this little program to replace a full word; like replace apple with orange

Our first line will remain the same.

Sentence = input(“Please enter a sentence:”)

 

Our second line of course will be changed to meet the new criteria

Sentence = Sentence.replace(‘apple’, ‘orange’)

 

We need to take account that someone may capitalize Apple and Orange, so we add a line to our code to capture this.

Sentence = Sentence.replace(‘Apple’, ‘Orange’)

 

And of course we print just like the last program

print(Sentence)

 

Full Program:

Sentence = input(“Please enter a sentence:”)

Sentence = Sentence.replace(‘apple’, ‘orange’)

Sentence = Sentence.replace(‘Apple’, ‘Orange’)

print(Sentence)

 

Lets input a sentence like, I do love an apple in the morning. You should eat an Apple every day…

Simple!

http://www.unleashthepython.com

Word and character counter; Python Programming

word count

This short program asks a user to input a string. It then counts each character and each complete word the user enters. Finally it prints this information to the screen.

We will break the program down a bit to start so as not to confuse ourselves. We will start with getting the user information and counting the number of characters entered.

We ask the user to enter a string and store it in a variable we called sentence

sentence = input(“Enter a string:”)

Next we create a variable called chars to count the number of characters entered. We assign this the value 0 as it will be empty to start.

chars = 0

Next we create a variable called words and assign it the value 1. We do this as the program will only start counting after the first word is created. We need to add the first word to the count to keep it accurate.

words = 1

Now we need a for loop to iterate through the variable sentence (where the string is stored). We will ask it to check each character in the variable sentence. For each character it counts in the variable sentence; add 1 to the variable chars and assign that to itself.

for characters in sentence:

        chars = chars + 1

 

Print the text and the variable chars to the screen;

 

print(“Number of characters in the string:”, chars)

 

Try running this program and see if it works;

 

sentence = input(“Enter a string:”)

chars = 0

words = 1              # will be used in the next part of the program

for characters in sentence:          

        chars = chars + 1

        print(“Number of characters in the string:”, chars)

 

Now we need to also count the words. We already have the variable words assigned to 1. The only extra bit we need to add is an if statement looking for a space between characters. If we find a space we can safely assume it’s a new word.

for characters in sentence:

        chars = chars + 1

       if(characters == ‘ ‘):          # looks for an empty space.                                    

               words = words+1    # adds 1 to the word count

 

lastly we add a print statement for the amount of words

print(“The number of words in the string is:”, words)

 

Now for the full program:

sentence = input(“Enter a string:”)

sentence = input(“Enter a string:”)

chars = 0

words = 1

for characters in sentence:

        chars = chars + 1

       if(characters == ‘ ‘):

                words = words+

print(“The number of words in the string is:”, words)

print(“Number of characters in the string:”, chars)

Check whether a number is positive or negative. Python Programming

neg

As the title suggests, the purpose of this program is to tell you whether the number you enter is a positive or a negative number. 

Lets get some input from the user. We need to convert it to an integer using int and assign the input to a variable we are going to call number. Don’t forget the double brackets.

number = int(input(“Enter a number: “))

Now the engine of the program; the if statements. The first to test whether the number entered is smaller than 0. If so then its a negative number..

if number < 0:

        print(“This number is negative.”)

Next we need to take care of numbers is bigger than 0, which of course is a positive

elif number > 0:

        print(“This number is positive.”)

Now we need to account for the fact that the user may enter a 0

elif number == 0:

        print(“You have entered Zero”)

 

Now test this. Input 0, -1 and 6 for instance. Just to test that its working.

It is a bit inconvenient having to keep restarting the program, so lets add a while loop..

 

Lets create a random variable and just call it var. Again lets assign it a random number, say 1

var = 1

In order to keep the while loop alive we must ensure its always equivalent to 1

while var = 1:

 

now we just stick our code underneath. Don’t forget to indent.

 

The full Program:

Don’t forget the indents after the while and if statements

var = 1

while var == 1:

        number = int(input(“Enter a number: “)) 

        if number < 0:

                print(“This number is negative.”)

       elif number > 0:

               print(“This number is positive.”)

       elif number == 0:

              print(“You have entered Zero”)

 

And there we go, another simple Python Program!

http://www.unleashthepython.com 

Palindrome, Python Programming

words

A palindrome is a word that reads the same backwards as it does forwards. An example of a palindrome is Anna, refer and racecar.

I will take you through this simple little program step by step. The complete program is available at the end.

A while loop is required in order to keep the program functioning.  Otherwise it would close after the first input.

 

var = 1   # you can use any arbitrary word or number. I just picked 1

while var == 1:    # this just keeps the while loop running

 

Next we take input from the user. This is stored in the variable word. Don’t forget to indent the code because it comes under the while loop.

    

            word = input(” Please enter a word “)

 

This is where it becomes interesting. We assign the variable word (where we just stored the user input) to a new variable called reverse. However, we use -1 to store the input backwards.

 

word[::] is the same as just printing the contents of variable word. Putting -1 with the two :: reads the input stored in the variable backwards, so;

 

                reverse = word[::-1] 

 

We can now use an if statement to evaluate whether the input entered by the user is in fact a palindrome.

 

              if word == reverse: # if the two words are the same

                                print(word + ” is a palindrome, go again… “)                       

                else:      

                                print(“sorry ” + word + ” is not a palindrome, try again “)

 

The Complete Program as follows;

var = 1

while var == 1:            

                word = input(” Please enter a word “)   

                reverse = word[::-1]  

                if word == reverse:

                                print(word + ” is a palindrome, go again… “)          

                else:     

                                print(“sorry ” + word + ” is not a palindrome, try again “)

 

And that’s it, the program will tell you whether it is a palindrome or not!

Check out http://www.unleashthepython.com for more

 

Rock Paper Scissors Python Programming

rock

Rock Paper Scissors is a decision based game and so can easily be replicated as a computer program.

As usual you can write this program in any text editor. I wrote mine in Notepad++

You can name it what ever you want as long as you save it with the .py extension.  I named my file rock.py

You can then run if from the console or by double clicking on the file itself.

You will see \n used throughout the program. This is an instruction to the program to start on a new line. the n will not show up when your program runs.

Now to the program. Being decision based, the if statement playing a starring role. The while loop is used to keep the program running until we decide to close it.

Rock Paper Scissors is a two-person game. We therefore need to create a variable to store the name of each of the the two players. In another post we will look at playing against the computer. For now though we will keep it as a two player game and assign two variables,  one for each player. This is done via an input statement;

 name_one = input(“Please enter name of Player 1 “)

name_two = input(“Please enter name of Player 2 “)

Now we need to ensure the game keeps running until the user decides to close it. For this we use a while loop. We first create an arbitrary variable; var (it can be called anything) and assign it to an arbitrary number; in this case 1 (any number will do).

We use this opportunity to give instructions to the user using a print statement.

var = 1

 print(“Control + C to end at any time… “)

The while loop is designed to keep running while var is equal to 1. In other words, the loop stays open because it’s condition is valid.

while var == 1:

We now create a variable to store the choice of the two players. We give each player a choice of rock paper or scissors. The player will be instructed to pick a number from 1 to 3 to denote their choice. The choice is stored in the respective variables.

player_one = input(“Hi ” + name_one + ”  enter:\n\n 1 for Rock\n 2 for Paper\n 3 for Scissors\n “)

 player_two = input(“Hi ” + name_two +  ”  enter:\n\n 1 for Rock\n 2 for Paper\n 3 for Scissors\n\n “)

Now to the engine of the program. If statements are used to evaluate each of the possible combinations. i.e. Player 1 chooses rock and Player 2 chooses paper etc.

 

 if player_one == “1” and player_two == “2”:

 print(“Paper beats Rock: ” + name_one + ” you are the winner “)

 

elif player_one == “2” and player_two == “1”:

 print(“Paper beats Rock: ” + name_two + ” you are the winner “)

 

if player_one == “2” and player_two == “3”:

print(“Scissors beats Paper ” + name_one + ” you are the winner “)

 

elif player_one == “3” and player_two == “2”:

print(“Scissors beats Paper ” + name_two + ” you are the winner “)

  

if player_one == “1” and player_two == “3”:

 print(“Rock beats Scissors ” + name_one + ” you are the winner “)

 

elif player_one == “3” and player_two == “1”:

print(“Rock beats Scissors ” + name_two + ” you are the winner “)

 

If both players pick the same option; then it is a draw.

elif player_one == player_two:
       print(” Its a draw \n”)

 

Now for the Complete program:
name_one = input(“Please enter name of Player 1 “)
name_two = input(“Please enter name of Player 2 “)
var = 1

print(“Control + C to end at any time…\n”)
while var == 1:

player_one = input(” Hi ” + name_one + ” enter:\n\n 1 for Rock, 2 for Paper, 3 for            Scissors\n\n “)

player_two = input(” Hi ” + name_two + ” enter:\n\n 1 for Rock, 2 for Paper, 3 for Scissors\n\n “)

if player_one == “1” and player_two == “2”:
        print(“Paper beats Rock: ” + name_one + ” you are the winner \n”)

elif player_one == “2” and player_two == “1”:
       print(“Paper beats Rock: ” + name_two + ” you are the winner \n”)

if player_one == “2” and player_two == “3”:
       print(“Scissors beats Paper ” + name_one + ” you are the winner \n”)

elif player_one == “3” and player_two == “2”:
      print(“Scissors beats Paper ” + name_two + ” you are the winner \n”)

if player_one == “1” and player_two == “3”:
       print(“Rock beats Scissors ” + name_one + ” you are the winner \n”)

elif player_one == “3” and player_two == “1”:
       print(“Rock beats Scissors ” + name_two + ” you are the winner \n”)

elif player_one == player_two:
       print(” Its a draw \n”)