Showing posts with label Python Code. Show all posts
Showing posts with label Python Code. Show all posts

Learn Python the Easy Way

Learn python programming in 12 lessons


Learning to write code is easy and anyone with access to a computer can do it and it will probably force your brain to approach problem solving from a different angle. Python is one of the many programming languages you can learn and it's so simple yet powerful and was at one point the backend code used by YoutTube and currently used by Instagram.

This is an introduction to Python programming to help you get started before moving onto other sources and complex constructs. Use this as a glossary to help you keep track of where you need to go.

Lessons

 

Miscellaneous

 

read more

Lesson 4: Input, Output and Assignments

Learn python programming in 12 lessons


A python program can also accept input from the user and this is used by the input() function. The python program AddThreeNums.py can be updated to accept input from a user and store them in the three variables as follow


num1 = input(“Enter the first number”)
num2 = input(“Enter the second number”)
num3 = input(“Enter the third number”)

total = eval(num1) + eval(num1) + eval(num4)
average = total/3

print(“Total”, total)
print(“Average”, average)

The eval function is used to convert a string that is a number into an integer.

The print function used to provide the output to the screen is an interesting function. In Python 3, you are able to change a number of things in the printing pattern of any expression. When printing(1,2,3,4,5), The print command automatically inserts a space between the numbers separated by the commas. Those spaces can be replaced by any character sequence of your choice such as print(1,2,3,4,5,sep=‘’) which would print 12345 with no spaces.

>>> print(1,2,3,4,5)

1 2 3 4 5

>>> print(1,2,3,4,5,sep='')

12345

>>> print(1,2,3,4,5,sep='=')

1=2=3=4=5

>>> print(1,2,3,4,5,sep='&')

1&2&3&4&5

>>> print(1,2,3,4,5,sep='*')

1*2*3*4*5

>>> print(1,2,3,4,5,sep='no')

1no2no3no4no5

>>> print(1,2,3,4,5,sep='!')

1!2!3!4!5

Also take note that the print function automatically prints a new line once it has run out of things to print. This newline brings the cursor to the next line to print a different sequence on a new line. To change the end character from a newline to any character of your choice, the end keyword is used. The end keyword can be used as follows


>>> print(1,2,3,4,5,end=’STOP')

1 2 3 4 5STOP>>>

>>> print(1,2,3,4,5,sep=‘no’,end=‘*')

1no2no3no4no5*>>>

>>> print(1,2,sep=‘no’,end=‘\n')

1no2

>>> print(1,sep=‘no’,end=‘*')

1*>>>

You should take note that the sep keyword is only invoked if there is another item in the printing queue. The end keyword is only invoked once the printing queue is empty.

There are a number of predefined characters that can be used with the print function such as a tab denoted by \t and a single quote denoted by \’. The use of a backslash is called escaping the character sequence and to print the backslash, you have to escape it as \\. The first backslash encountered in the printing sequence notifies the interpreter that the next character is not there by mistake but you actually wish to print it as it appear. Here are a list of other character sequence escaped in Python.
\t --> tab
\n --> new line
\b --> back space
\s --> space
\" --> quotation mark (")
\' --> apostrophe (')

You have already encountered assignments in Python in the program AddThreeNums.py program above and one such example is average=total/3. Python can also do multiple assignments on the same line like


w,x,y,z = 1,2,3,4

The above assignment is equivalent to


w = 1

x = 2

y = 3

z = 4

Python is also able to handle double swapping assignments in one line without the need to have a temporary variable to facilitate the process. Say you wanted the numbers in x and y above to be swapped, you could introduce a new variable and do the swap like this


temp = x

x = y

y = temp

The three lines above are equivalent to the single line  
x,y = y,x
read more

Lesson 3: A Python Program

Learn python programming in 12 lessons


Python programs are identified by the file extension “.py" for example HelloWorld.py would be the python file containing the Hello World program.

A python program would contain any of the elements below
  1. Variables: used to provide easily identifiable names to objects example of good names for variables are x, y, z, name, boy, girl, school, this_school, my_wallet, thisSchool, myWallet, etc
  2. Functions: used to perform evaluations on parameters e.g. sqrt(4)
  3. assignments statements: used to associates variables with objects e.g. x=6
  4. Input statements: used to request input from the user. This are easily identified by the input() function. e.g. input(“Please enter a number: “)
  5. Output statements: used to display items on the screen. This are given by the print() function. e.g print(“Hello world!”)
  6. Comments: used to provide clarity to future programmer reading your code. Any line of code preceded by # in python is regarded as a comment and would be ignored when the program is executed.
When naming your program, function or variable, you would want to not use a reserved python word such as def, del, is, in, import, while, etc. Look at the complete list of reserved word in Python and know them by heart. The following line of code does just that.

import keyword
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Now that you are aware of some of the elements of a program, you should be ready to start writing your own python programs. The program below calculates the average of three numbers and displays it on the screen.
#Program to display the average of three numbers on the screen
#program name: AddThreeNums.py

num1 = 1
num2 = 2
num3 = 3


total = num1 + num2 + num3
average = total/3


print(total)
print(average)
This program would output
6
2

This would be considered as a bad program because it does not inform the user of the program as to what the 6 and 2 represents. It would be ideal to display total and average next to their corresponding values. The program below is an improvement to the first
#Program to display the average of three numbers on the screen

num1 = 1
num2 = 2
num3 = 3


total = num1 + num2 + num3
average = total/3


print(“Total”, total)
print(“Average”, average)
The correct output would be
Total: 6
Average: 2.0

If your program gives a different output other than the one above, then you are probably not using python 3. Note that average is a double number and to convert it to an integer, enclose it like int(average) to get the output below.
Total: 6
Average: 2
read more

The Python Series

Learn python programming in 12 lessons


When most people hear of Python, they think of the big snake native to most African and Asian countries. For others, Python is one of the most popular high level programming language used today in the industry and academic institutions because of its ease to learn and create code fairly quickly. 
It is mostly common amongst mathematicians, physicist, etc because of its ability to handle big number better than other programming languages such as Java.

Python was created in the late 1980s by a Dutch programmer called Guido van Rossum and he specifically chose to call it Python not after the snake but after a British sketch comedy show called Monty Python.

If you are interested in learning how to write code's, python would be the best language to learn because as powerful as its is, it has the easiest syntax and due to its popularity, you are never going to run out of reference materials.

To start programming in Python, you will need to go to the Python Software Foundation website and get the latest source code, preferably Python 3.* You can still still use Python 2 if you are using a reference book that was written before 2009 which is still going to be OK but for enhanced features and security patches, pick the latest.

The next thing you will need is an Integrated Development Environment known as an IDE and there are a lot of them on the market. Pick the one that is free, small and has a simplified graphical user interface with debugging capability. The debug tool is really important especially for an amateur programmer because it will help you spot part of the code that is producing unwanted results. There are lots of IDE on the market, but you can start with free IDEs such as PyCharm or Wingware.

Programming guru's do not really need IDE, a simple notepad will get the job done and the program is executed via the command line. Whilst we are talking about notepad, you might also want to get yourself Notepad++ and Sublime Text  to use when you reach the point where you can code without an IDE.

One of the most important resource you are going to need is a reference book to help you understand some of the concepts better. A hard copy book is important because it will still be able to guide you way better especially in cases where you have no access to the internet to look up concepts that are bothering you. If you cannot find a good book in your local bookstore, look at getting anyone of these books from Amazon.
  1. Learning Python by Mark Lutz
  2. Python Programming for Begginers by Jason Cannon
  3. Python programming by John Zelle
That's pretty much all you need to start learning programming concepts by using Python. Click and bookmark the label The Python Series to see all posts related to Python. This series of post won't cover the hardcore stuffs, just the basics to get you interested in programming with Python.
read more

We Only Desire The New Device


Came across one of those unusual article the The Onion about the undesirable device and it got me appreciating just how brilliant that article is. I found it brilliant because it was written generic in such a way that it can be applied to pretty much any device regardless of its manufacturer. One can't help but think this article was written to poke fun of iPhone enthusiasts.

There are 11 key variables you have to take note of:
1. The old device
2. The new device
3. Nationality of consumers
4. The manufacturer
5. The manufacturer spokesperson
6. The selling price
7. Consumer 1: owns old device
8. Consumer 2: just got the new device
9. Consumer 3: showing off the new device
10. The device enthusiast
11. Location from where article is posted

Now that you are aware of the key variables in the article, you can pretty much replace everything in the article with the 11 variables. You can pretty much just put all this in a programming language and insert all the variables in and whip out a number of your own customized articles.

I will name the variables like this:

  1. oldDevice
  2. newDevice
  3. nationality
  4. manufacturer
  5. spokesperson (has first and last name)
  6. sellingPrice
  7. consumerOne (has first and last name)
  8. consumerTwo (has first and last name)
  9. consumerThree (has first and last name)
  10. enthusiast (has first and last name)
  11. location

I will put the generic article with all variables inserted in and you can have fun creating your own articles.

<location>—With the holiday shopping season officially under way, millions of consumers proceeded to their nearest commercial centers this week in hopes of acquiring the latest, and therefore most desirable, personal device.

"The new <newDevice> is an improvement over the old <oldDevice>, making it more attractive for purchase by all <Nationality>," said <spokesperson>, a spokesperson for the large conglomerate that manufactures the new device. "The old <oldDevice> is no longer sufficient. Consumers should no longer have any use or longing for the old <oldDevice>."

Added <spokespersonLastName>, "The new <newDevice> will retail for $<sellingPrice>."

Able to remain operational for longer periods of time and occupy a demonstrably smaller three-dimensional space, the new <newDevice> is so advanced when compared to the old <oldDevice> that it makes the old <oldDevice> appear much older than it actually is. However, the new <newDevice> is reportedly not so radically different as to cause confusion or unwanted anxiety among those familiar with the feel of the old <oldDevice>.

"Its higher price indicates to me that it is superior, and that not everyone will be able to afford it, which only makes me want to possess it more," said <consumerOne>, owner of the old <oldDevice>, which he obtained 18 months ago when it was still the new <oldDevice>. "I feel a strong urge to purchase the new <newDevice>. Owning the new <newDevice> will please me and improve my daily life."

"It's difficult to remember how I ever found enjoyment in my old <oldDevice>," <consumerOneLastName> continued. "It is no longer appealing to the eye."

In addition to aesthetic and technological enhancements, <manufacturer> claim the new <newDevice> comes equipped with a wide range of desirable features, including fewer buttons for pressing down and holding; a new wire for connecting to larger, less-portable devices; and fewer device-related errors and frustrations.

The new <newDevice> will also be available in blue.

"Not only will I be able to perform tasks faster than before, but my new <newDevice> will also inform those around me that I am a successful individual who is up on the latest trends," said <consumerTwo>, whose executive job allowed her to line up for several hours in the middle of the day in order to obtain the previously unavailable item. "Its attractiveness and considerable value are, by extension, my attractiveness and considerable value."

Consumer <consumerThree> agreed.

"I'm going to take my new <newDevice> wherever I go," said <consumerThreeLastName>, holding the expensive item directly in the eyeline of several reporters. "That way no one on the street, inside the elevator, or at my place of business will ever mistake me for the sort of individual who does not own the new <newDevice>."

Added <consumerThreeLastName>, "The new <newDevice> brings me satisfaction."

Despite the visible excitement among most consumers, some claimed to be exercising caution, choosing instead to sit back and wait for a newer version of the new <newDevice> to be released before making a purchase.

"True, it appeals to my most basic insecurities, but this new <newDevice> will ultimately be replaced by a newer device, rendering it completely undesirable and utterly repellent to my personal tastes," device-enthusiast <enthusiast> said. "Also, I should start saving my money for the next latest device, which will replace the newer new <newDevice> a couple months after that."


I will use the generic article above to talk about the new iPhone
These will be the variables:

  1. oldDevice: iPhone 6
  2. newDevice: iPhone 7
  3. nationality: American
  4. manufacturer: Apple
  5. spokesperson: Chris Gaither
  6. sellingPrice: 449
  7. consumerOne: Eric Rottenberg
  8. consumerTwo: Allison Berding
  9. consumerThree: Sean Johnson
  10. enthusiast: John Appleseed
  11. location: Cupertino

Just look at how the generic article works if variables above are substituted in.


CUPERTINO—With the holiday shopping season officially under way, millions of consumers proceeded to their nearest commercial centers this week in hopes of acquiring the latest, and therefore most desirable, personal device.

"The new iPhone 7 is an improvement over the old iPhone 6 making it more attractive for purchase by all American," said Chris Gaither, a spokesperson for the large conglomerate that manufactures the new device. "The old iPhone 6 is no longer sufficient. Consumers should no longer have any use or longing for the old iPhone 6."

Added Gaither, "The new iPhone 7 will retail for $449."

Able to remain operational for longer periods of time and occupy a demonstrably smaller three-dimensional space, the new iPhone 7 is so advanced when compared to the old iPhone 6 that it makes the old iPhone 6 appear much older than it actually is. However, the new iPhone 7 is reportedly not so radically different as to cause confusion or unwanted anxiety among those familiar with the feel of the old iPhone 6.

"Its higher price indicates to me that it is superior, and that not everyone will be able to afford it, which only makes me want to possess it more," said Eric Rottenberg, owner of the old iPhone 6, which he obtained 18 months ago when it was still the new iPhone 6. "I feel a strong urge to purchase the new iPhone 7. Owning the new iPhone 7 will please me and improve my daily life."

"It's difficult to remember how I ever found enjoyment in my old iPhone 6," Rottenberg continued. "It is no longer appealing to the eye."

In addition to aesthetic and technological enhancements, Apple claim the new iPhone 7 comes equipped with a wide range of desirable features, including fewer buttons for pressing down and holding; a new wire for connecting to larger, less-portable devices; and fewer device-related errors and frustrations.

The new iPhone 7 will also be available in blue.

"Not only will I be able to perform tasks faster than before, but my new iPhone 7 will also inform those around me that I am a successful individual who is up on the latest trends," said Allison Berding, whose executive job allowed her to line up for several hours in the middle of the day in order to obtain the previously unavailable item. "Its attractiveness and considerable value are, by extension, my attractiveness and considerable value."

Consumer Sean Johnson agreed.

"I'm going to take my new iPhone 7 wherever I go," said Johnson, holding the expensive item directly in the eyeline of several reporters. "That way no one on the street, inside the elevator, or at my place of business will ever mistake me for the sort of individual who does not own the new iPhone 7."

Added Johnson, "The new iPhone 7 brings me satisfaction."

Despite the visible excitement among most consumers, some claimed to be exercising caution, choosing instead to sit back and wait for a newer version of the new iPhone 7 to be released before making a purchase.

"True, it appeals to my most basic insecurities, but this new iPhone 7 will ultimately be replaced by a newer device, rendering it completely undesirable and utterly repellent to my personal tastes," device-enthusiast John Appleseed said. "Also, I should start saving my money for the next latest device, which will replace the newer new iPhone 7 a couple months after that."
read more