elif code, while loops, logical operators

More on elif

# Fortune program. More fun if you implement your own!

import random

print(“I’m going to predict your fortune for today.”)

fortune = random.randint(1, 3) # 3 possible fortunes

if fortune == 1: # if fortune is equal to 1

print(“\n\tIn the mountains of truth you will never climb in vain.”)

elif fortune == 2: # else if the fortune is equal to 2

print(“\n\tIn the middle of winter I at last discovered that there was in me an invincible summer.”)

elif fortune == 3:

print(“\n\tThere can be no doubt that all our knowledge begins with experience.”)

else:

print(“This should never occur, but demonstrates else being used defensively in case of error”)

While loops

These occur in real, mundane life. “While your hands are dirty: rinse with water. Lather with soap. Repeat.” Whilst your hands are dirty, the loop repeats, because dirty still evaluates to True. It breaks out of it once your hands are clean (dirty becomes False).

# Annoying program

print(“It seems you dont have anti-virus software installed!\n”)

response = “” # sentry variable

while response != “No.”:

response = input(“Install anti-virus software now!\n”)

print(“OK. I’ll try somebody else!”)

input(“\n\nPress enter to exit.”)

As soon as you enter “No.” it will break out of the loop, because you’ve broken the condition the loop was set to. It was saying when your response was not equal to “No.”, it will keep repeating itself in a loop.

The reponse = “” is called a sentry variable. It is a barrier around the block of the while loop, and of course, every time we input something, we’re updating the response variable. You should initialise a sentry variable before your loop. If you put it in, you’ll have an infinite loop. Welcome to the club. :-)

Infinite loop

# Quick way to join the club

penguin = 0

while penguin <= 0:

print(penguin)

Values — True and False

I’ve mentioned these 2 values a lot. In Python any value is true or false. Integers, decimal numbers, and strings are true. 0 and “” (empty string) are false. Programmers test for empty values, perhaps to make sure the user input a number, etc.

print(“Would you like to make a donation to the programmer’s trust fund?”)

donation = int(input(“How much would you like to donate to the cause?”))

if donation:

print(“Thanks very much!”)

else:

print(“You chose not to donate anything to the cause.”)

  • Notice “if donation:” — it means “if there is a donation” as well as meaning if donation != 0.
  • It’s a clear, elegant way of saying it. It relates back to its true and false values.

Break and Continue statement

var = 0

while True:

count += 1

if count > 10:

break

if count == 7:

continue

print(count)

  1. As soon as the count variable reaches 10, it breaks out of the loop.
  2. When count hits 7, it skips the rest of the loop, skips 7, and goes back through the loop.
  3. Try running this, and with your own numbers.

Logical Operators: and, or, not

# Favourite colour and favourite day clubs

print(“\tLet’s see what groups you fall in to”)

colour = “”

while not colour:

colour = input(“Favourite colour?: “)

day = “”

while not day:

day = input(“Favourite day?: “)

if colour == “red” and day == “monday”:

print(“You’re in the ‘Red Mondays’ group!”)

elif colour == “blue” and day == “tuesday”:

print(“You’re part of the ‘Blue Tuesdays’ group!”)

# and so on and so forth

else:

print(“I was too lazy to come up with more options..”)

input(“\n\n\tHit enter to quit”)

  • The user has to enter some of the (limited) options before I let them continue through the loop.
  • Using the logical not operator spawns a phrase to mean the opposite of the original.
  • username starts out as false – an empty string
  • Soon as the user enters something, the value is true, and then proceeds through the loop

username : not username

True : False

False : True

and is straight forward. Put it between 2 conditions when you want a new condition that is true if both of them are true.

You walk into a shop. You want to buy oranges and apples. You’ll only buy if they have both of them.

or is also simple. 1 of the conditions has to be true.

You want to buy oranges or apples. If they had only one fruit, you’d still buy.

 

Posted in programming | Leave a comment

If, else, elif; random, comparison operators, log-in program

The programs you’ve created are read by Python from top to bottom in a sequential order. This makes things difficult, if that’s all we could do.

Random Numbers

In your editor:

import random

var = random.randint(1, 5)

You import Python’s random module using the import statement. randint is a function in the random module. In the brackets the values 1, 2, 3, 4, 5 have been given (“1 to 5″). (1, 10) would return the series of numbers 1 through to 10.

Code

print(“Here’s an example using a log in scenario. What’s the password?”)

password = input(“Enter the password: “)

if password == “strawberry”:

print(“Password accepted”) # Make sure to indent/tab this line, and following lines in the block**

else:

print(“Not accepted, try again”)

if statement

if, else, and elif (“else if”) — referred to as branching. We can make decisions based on conditions. The one I used above: if the input is equal to* “strawberry” it accepts it, otherwise it doesn’t. The statement is either True or False. Try it out.

else clause

  • A way to say “if <condition> evaluates to True, do that. Otherwise (else), do this”
  • If you have more possible outcomes, use elif (“else if”) instead of else.

*Comparison Operators

Used to compare values. == means “equal to”. Some more to follow. Try the examples in the shell:

Operator : Meaning : Example : Evaluates

== : equal to : 3 == 3 : True

!= : not equal to : 9 != 4 : True

> : greater than : 2 > 8 : False

< : less than : 4 < 7 : False

>= : greater than or equal to : 4 >= 9 : False

<= : less than or equal to : 3 <= 3 : True

**Indentation/”Tabbing”/Whitespace

Requirement in Python. Good hygiene for other languages. After a statement that ends in a colon : indent the code in that “block” with your tab key. IDLE does this for you.



 

Posted in programming | Leave a comment

Converting Values, Shortcuts and Homework

So, that broken program is printing the value of the strings we entered, and not treating them as integers. Converting those values to strings:

apple = int(input(“”How many apples?”))

Shortcuts – Quite Useful

var*=5 is the same as: var = var*5

var/=5 : var = var/5

var%=5 : var = var%5

var+=5 : var = var+5

var-=5 : var = var-5

Challenges

  1. Write a program where you enter your first name and your surname. It then prints out your full name.
  2. You want to tip the waiter. Enter the bill total. Display the amounts for 2 different tips.
  3. You sell computers. Give a base price for the computer and then add extra fees: software, installation support, delivery, and VAT. At least 2 should be percentages of the base price. Display the full amount of a computer with the extras.


Posted in programming | Leave a comment

Variables

Moving more into the realms of real programming. Variables are storing values we set.

In your shell:

name = “your name”

print(name)

print(“You used a variable, ” name)

name is the variable, your name is the value you bound to it.

  • Variables need letters, numbers, and underscores _, and can’t start with numbers.

Input Function

In your shell, feel free to create a program, too:

name = input(“What is your name?”)

print(name)

print(“Your name is “, name)

Here’s a program. Paste it into a new python file (fruit.py).

print(“Make your own fruit salad. How many of each do you want”)

apple = input(“How many apples?”)

orange = input(“How many oranges?”)

banana = input(“How many bananas?”)

mango = input(“How many mangos?”)

squash = input(“How many squashes?”)

guava = input(“How many guavas?”)

total = apple + orange + banana + mango + squash + guava

print(“The total of all your fruit is: “, total)

input(“\n\nHit enter to exit.”)

 

 

Posted in programming | Leave a comment

“Strings” + Maths Operators

We’ve seen strings already, but we were printing them like print(“This is a string”)

In those quotes is the string. You might have a program with an introduction paragraph. You might want to format it.

Get your shell ready, and type these:

print(“This is a good example of ‘Strings’ because one is inside another, as a quote”)

print(“Yet”, “another”, “example of strings”, “separated with commas”)

print(“This one”,

“spans across”,

“multiple lines”)

You can use single quotes ‘ or double ” — it doesn’t matter. Multiple lines makes paragraphs easier to read. If you opened a string with a double quote, end with a double. If you nest a quote in that string, wrap single quotes around it. “Just ‘like’ this”

Joining Strings Together

print(“You can now see ” + “the ‘+’ operator” + “being used to join strings together”)

Let’s try a long one.

print(“\nThis is a really long string ” + “that will demonstrate ” + “how to ” + “join strings together ” \
+ “and carry them ” + “onto new lines” + ” the \\ character is\n” + “doing that” \
+ “for” + “us”)

Now let’s try something more interesting:

print(“Something more interesting.” * 10)

Escape sequences

You’ve seen a few already. Try use them with your strings.

\\ – to print a backslash

\’ – To print a single quote i.e. print(“Here\’s how to print a single quote.”)

\a – Apparently sounds the system bell. Never tried it myself.

\n – Newline

\t – tab indent

Mathematics and (common) Operators

Some examples — try them out in the shell:

2 + 2 addition

5 – 1 subtraction

5 * 5 multiplication

10/2 true division

7//3 floor division

7%3 remainder of the division

2**3 raises to a power (2x2x2)

 

 

Posted in programming | Leave a comment

First Program, Et al.

In the interactive shell, type, and hit enter:

print(“This is the interactive shell.”)

  • print (case-sensitive, all lowercase) is a function. It’s a program itself found in most programming languages.
  • The text in the quotes is called a string. A type of data.
  • You wrote your first program, and were presented with immediate feedback.
  1. Open up the IDLE editor File > New Window, and enter the same text.
  2. Save and run it (Press F5). So the editor allows you to create programs that you can save.

Comments are text prefixed with a #, and are ignored in programs. Great way to annotate code, so you and others can understand it.

print(“Hello, World!”) # Prints text to the screen

input(“\nPress a key to exit”)

input is another function for dealing with user input. \n is an “escape sequence” that operates on a “new line”. There’s also “\t”, for “tab”. Try it.

Challenges:

  1. Print some text, like “Hello, World!”, your name, etc, in both the shell and as programs via the editor.
  2. Insert comments into your print programs (above the print line, below it, on the same line…)
  3. Write a program that prints something on the first line, and on the second with a indented tab, and requires you to press enter before it ends.
Posted in programming | Leave a comment

Python 3 – How To Install

IDLE is what comes with the Python download. It comprises of an editor, where you’ll type out programs, and the interactive shell, where you can test bits out. Fire it up from the start menu -> (Python IDLE GUI).

  • Python interactive shell. That >>> is a prompt. It’s waiting for your input
  • Type 2+2 like I have.
  • It’s interactive. Let’s move on.

 

Posted in programming | Leave a comment

Optional Introductory

You don’t have to read this. It just explains my approach.

  • Any new hobby, interest or skill takes time to learn.
  1. Learn computer programming, without all the fuss and extra baggage
  2. “Try before you buy.” (Learn Python before dedicating your time to it.)
  3. Learn the basics — learn how to program, because that’s what you want.

You won’t find philosophical anecdotes. This is a no-nonsense approach to get the job done.

  • Expect to come to terms with enough to read and write some stimulating code
  • You’ll learn enough to complete challenges I’ll set for you

Far too many resources are tutorials, explanations, manuals, tomes where the authors cram in all their knowledge. You could sit and read them all (as great as they are), absorb the philosophies, learn the jargon, quote multiple paradigms, yet still find yourself unable to write anything.

If you like what I cover here, go and look for more. Thanks to the web, there are free resources everywhere. They may help you with the challenges here, or maybe some you’ll set yourself.

 

Posted in programming | Leave a comment