Hour 1
Hands-On Programming

You have this book because you want to go further than the typical computer user. You don’t just want to use computers; you want to write programs for them. You want the skills necessary to make computers do exactly what you want.

This 24-hour tutorial shows that you don’t have to be a wizard to become a proficient (or even an expert) programmer. By the time you finish this one-hour lesson, you will have reviewed your first computer program and its results. This chapter springboards you into programming so you can get a feel for programming right away. Once you’ve had this hands-on experience, subsequent hours will explain more of the background you need to understand how to design and write programs.

The highlights of this hour include the following:

Image Learning what a program does

Image Understanding the truth behind common programming myths

Image Mastering source code concepts

Image Reviewing your first program

Get Ready to Program

You’ll find this hour divided into these two areas:

Image An introduction to the nature of programming

Image Hands-on practice with your first programming language

Most new programmers want to start programming right away. However, some background is necessary. This hour attempts to take care of both demands by offering an introductory background look at programming and then quickly jumping head-first into hands-on programming. If you went straight into a new programming language with absolutely no background first, you might miss the entire point of programming. So, the next few pages bring all readers up to a level playing field so that everyone who takes this 24-hour course can begin to write programs right away.

What a Computer Program Does

Most people today are surrounded by computers, and those computers are getting incredibly powerful. For example, the CPU that powers your smartphone is actually more powerful than the computer that was used to put the first man on the Moon. Not only do we have desktop and laptop computers, as well as tablets and smartphones, but appliances like televisions and your car have computers embedded in them. All those computers perform specific tasks, depending on where they are located. Your laptop can help you balance your checkbook or track your inventory if you run a business. Your phone is filled with apps to enhance productivity or have fun. The computer in your car helps maintain the vehicle’s temperature. These jobs happen thanks to computer programs that an individual or team created.

If you want to begin programming, chances are you have probably been using a computer for some time. Nevertheless, as a future programmer, you should review some fundamental computing concepts before you can master the ins and outs of a new computer language.

At its simplest level, a computer processes data. Figure 1.1 shows this as the primary goal of all computer programs. Many businesses call their computer programming departments data processing departments because computers process data into meaningful information. You may not have considered the difference between the words data and information before, but there is a tremendous difference to a computer professional. Raw data consists of facts and figures, such as hundreds of days of stock prices. A program might process that data into meaningful information, such as a line chart that shows the overall trend of the stock prices over time. It is the computer program that tells the computer what to do. Sometimes, a program might simply process data from another program without showing any output for the user. The processed data is still information because the program’s output, stored on the disk, is changed in some way. For example, a program that closes monthly account balances may collect data from various accounting systems in a company and combine, balance, and close that data, resetting the data for the following month.

images

FIGURE 1.1
Programs convert raw data into meaningful information.

A program is a list of detailed instructions that the computer carries out. The program is the driving force behind any job that a computer does. The computer cannot do anything without a program. It is the job of the programmer to design and write programs that direct the computer to transform raw data into meaningful information for the end user. The end user (usually just called the user) of the computer is generally the nontechnical, nonprogramming person who needs the results (the information) that the program provides.

You, as the programmer, are responsible for guiding the computer with the programs you write. Learning to program computers takes a while, but it is certainly rewarding. Computer programming offers the advantage of instant feedback, unlike a lot of other jobs you can train for.

Common Programming Misconceptions

This book aims directly at the heart of the matter: Computers are easy to use and easy to program. A computer is nothing more than a dumb machine that “knows” absolutely nothing. Without programs, the computer doesn’t know what to do. A computer is like a robot that waits on your every command and acts out your instructions exactly as you give them. Sometimes your program instructions are incorrect. If they are, the computer goes right ahead and attempts them anyway.

Note

Don’t fear computer programming. Computers are tools to help you get your job done. You can learn to program.

Many misconceptions about computers exist and stem from a lack of understanding about how computers work and what computers are physically capable of doing. This book wants to shoot down the myths and improve your understanding of these machines. You’ll be programming computers in no time. The computer is nothing more than a tool that helps you do certain types of work. The computer itself is not bad or good. A hammer is a tool you can use for good (to build houses) or for bad (to break things). A computer in the wrong hands can be used for bad purposes, but that isn’t the computer’s fault, any more than it is the hammer’s fault if someone misuses it.

The next three sections attack the three most popular computer myths. Have you heard any of them? Did you think some were true?

Myth 1: Only Math Experts Can Program Computers

Thank goodness this is a myth and not reality, or thousands of people would be out of work (including most computer book authors!). Computers would be elitist machines used by only the best engineers and scientists; the casual user could not master them. Computers would still be beneficial in some areas, but they would not provide the benefits that so many people can enjoy.

Not only can you be poor at math, you don’t even have to like math or have the desire to learn math to be a good computer programmer. The computer does all the math for you; that’s one of its jobs. There are countless expert computer programmers in the world who cannot tell you the area of a circle or the square root of 64. If you thought this myth was reality, you can relax.

Programming can provide beneficial side effects. It turns out that, as you become a better programmer, you may find your math skills improving. Developing programming skills tends to improve your overall capability for logical thinking, which underlies many skills in math as well. Therefore, being better in math might be a result of programming, but it’s not a prerequisite.

Tip

People who favor logic puzzles, crosswords, anagrams, and word-search games seem to adapt well to programming, but again, liking these gaming activities is not a programming prerequisite. You will find that you can learn to program computers—and actually become extremely good at it—without liking math, being good at math, or having any flair at all for puzzles or word games.

Myth 2: Computers Make Mistakes

You might have heard the adage “To err is human, but to really foul things up takes a computer!” This might be accurate—but only in that a computer is so very fast that it duplicates a person’s mistakes rapidly.

Computers do not make mistakes; people make mistakes. If you have heard a bank teller tell you that $24 was incorrectly deleted from your savings account because “the computer program made an error,” the teller probably has no idea what really happened. People program computers, people run them, and people enter the data that the computers process.

The odds of a computer randomly fouling up a customer’s bank balance are minute. Computers simply do not make random mistakes unless they are programmed incorrectly. Computers are finite machines; when given the same input, they always produce the same output. That is, computers always do the same things under the same conditions. Your job, as you learn to program, will be to reduce the chance of computer mistakes.

When a computer malfunctions, it does not make a simple mistake; rather, it really messes things up. When a computer fails, it typically breaks down completely, or a storage device breaks down, or the power goes out. Whatever happens, computers go all out when they have a problem, and it is usually very obvious when they have a problem. The good news is that computers rarely have problems.

Before people invented computers, banks kept all their records on ledger cards. When a teller found a mistake (possibly one that the teller had made), do you think the teller said, “The ledger card made a mistake”? Absolutely not. Computers can have mechanical problems, but the likelihood of small mistakes, such as an incorrect balance once in a while, is just too small to consider. Such mistakes are made by the people entering the data or by (gulp) the programmers.

Myth 3: Computers Are Difficult to Program

Computers are getting easier to use—and to program—every day. If you used a microwave, drove a car, or watched a television recently, then chances are good that you used a computer when you did. Did you know you were using a computer? Probably not. The makers of computers have found ways to integrate computers into your everyday life to monitor and correct problems that might otherwise occur without them.

Of course, if you are reading this book, you want to learn enough about computers to write your own programs. Writing computer programs does take more work than using a microwave oven’s computerized timer functions. The work, however, primarily involves getting down to the computer’s level and learning what it expects.

Not only are computers getting easier to program every day, but you have more opportunities to learn about them than ever before. Cable television channels are loaded with educational shows about using and programming computers. Books and videos on the subject are all around you. The Internet itself contains scores of classes on all aspects of computers and other topics. YouTube hosts hundreds of videos on programming. There is probably a computer programming class happening within 15 minutes of your house as you read this.

Many Programs Already Exist

Although there are many programs already written for you to use, sometimes you need a program that fills a specific need and you cannot find one that does exactly what you want. When you are done with this book, you will know exactly what you need to design and write your own programs.

Programmers Are in Demand

Look at help-wanted websites. You’ll find that there is a shortage of computer programmers. Amid the requests for Java programmers, C++ programmers, C# programmers, mobile app developers, systems analysts, senior systems analysts, object-oriented programmers, systems programmers, HTML coders, and application programmers, you may find yourself lost in a sea of uncertainty and TLAs (three-letter acronyms) that might, at first, seem hopeless. Do not fret; this book will help direct you toward areas of programming that might be right for you.

Hour 22, “How Companies Program,” explores the chain of computer jobs and describes what each type of programming job is all about. If you are just starting out, you probably won’t be able to go to work as the most senior-level programmer, but you will be surprised at the salary your programming skills can bring you.

The Real Value of Programs

Although the prices of individual computer programs are decreasing, companies and individual computer owners invest more and more in programs every year. Not only do people purchase new programs as they come out, they update the older versions of programs they already have.

Businesses and individuals must factor in the cost of programs when making computer decisions. Whereas an individual usually buys a computer—called hardware because the machine isn’t changed often or easily—and is done with the hardware purchasing for a while, the purchasing of programs—the software—never seems to end because software changes rapidly. For a future programmer, this is welcome news because it means a secure career. For the uninformed computer purchaser, the cost of software can be staggering.

A business must also factor in the on-staff and contract programmers and the time needed to write the programs it uses. More information on the programming and support staff appears in the next section.

Users Generally Don’t Own Programs

When a company purchases software, it most often purchases a software license. If a company wants to buy a word-processing program for 100 employees, legally it must purchase 100 copies of the program, or at least buy a site license that allows the company to use the software on more than one machine. When a company buys a program, it does not own the program. When you buy a record, you do not own the music; you have only purchased the rights to listen to the music. You cannot legally alter the music, record it, or give away recordings of it, and, most importantly, you cannot sell recordings that you make of it. The same is true for software that you buy. The license for individual software grants you permission to use the software on one computer at any one time.

Giving Computers Programs

Figure 1.2 shows the code for a simple program by a computer programmer. As a matter of fact, that computer programmer is about to be you after you create the code using Python.

Remember: A computer is only a machine. To give a machine instructions, your instructions might be fairly readable, as those in Figure 1.2 are, but the code (another name for a program’s instructions) must be fairly rigid and conform to a predefined set of rules and regulations according to the programming language you use. Therefore, to write a program in the Python programming language, you must conform to Python’s rules of proper command spelling and placement. This programming language grammar is called syntax. (And you thought syntax was just a levy placed on cigarettes and liquor!)

images

FIGURE 1.2
A program’s instructions are somewhat cryptic but human readable.

Note

It is important to understand that the first section of this book is teaching you the basics of computer programming using the Python language, but it is not a complete Python tutorial. This may seem like the same thing, but it is not. The aim of the book is to teach you basic computer programming techniques (with examples in Python code) in the first half of the book and introduce you to a variety of programming languages and jobs in the second half. There are scores of excellent books, including Teach Yourself Python in 24 Hours, also by Sams Publishing, that can take you through every in and out of the Python language. That book will take you far more in-depth into the language than this book. Now that we’ve properly calibrated your expectations, let’s get back to beginning programming!

Source Code

Even after you make the effort to learn a computer language such as Python, and after you go to the trouble of typing a well-formed and syntactically accurate program such as the one in Figure 1.2, your computer still will not be able to understand the program! The program you write is called source code. It is the source code that you write, manipulate, and correct. Your computer, on the other hand, can understand only machine language, a compact series of computer-readable instructions that make no sense to people. They make sense to some advanced computer gurus, but my general assertion stands that they don’t make sense to people.

Listing 1.1 shows machine language. Can you decipher any of it? Your computer can. Your computer loves machine language. Actually, it’s the only language your computer understands. And different computers understand their own versions of machine language, so what works on one type of computer will not necessarily work on another. It’s best to stay away from machine language and let products such as Python convert your higher-level language into machine language’s cryptic 1s and 0s.

LISTING 1.1 Machine language is extremely difficult for people to decipher

01100100
10111101
10010011
10010100
00001111
01010101
11111110

All programs you run on your computer, phone, or tablet, including Microsoft Word, Internet Explorer, and programming languages, are already converted into machine language. That’s why you can click a program’s icon, and the program begins immediately. No interpretation or compilation is required. By providing you with the machine language only, software vendors serve two purposes:

Image They give you programs that execute quickly, without the intervening compiling step.

Image They ensure that you don’t change the source code, thereby protecting their intellectual property.

Your First Program

The first program that you write will be simple. You may not understand much of it, and that’s fine. The goal here is not to explain the program details but to walk you through the entire process of the steps that are typical of computer programming:

  1. Type a program’s source code and save it.

  2. Run the program in whatever Python environment you choose to use (see Appendix A, “Installing Python,” for more about this topic). This book was written with the use of Jupyter notebooks (https://jupyter.org). Others use pycharm, Visual Studio, and others. Some just write code in text editors, but for beginners, you are best served picking an IDE and working with it. It’s ultimately a personal preference, and the code examples in this book will work on any IDE.

  3. If the page is not doing what you want and has errors, called bugs, you need to fix those bugs in your source code and repeat these steps. Hour 7, “Debugging Tools,” explains how to locate and fix common bugs. You may need to do some bug hunting earlier than Hour 7 if you experience problems with your programs in these first few hours. If a program does not work as described, you will need to compare your source code very carefully to the code in the book and fix any discrepancies before saving it again.

Starting with Python

You can write your Python code in a number of different environments, and you can also choose between the latest version, Python 3, or Python 2. This book uses the latter, but for basic programming topics, there is little to worry about in terms of difference between the two. If you end up working on some existing Python projects, they may be incompatible with Python 3, but the newer version is still the better learning option. No matter which version of Python you choose, it is best to write your program in that version’s IDE or a text editor. (Not to scare you with another three-letter acronym right off the bat, but IDE stands for integrated development environment, which is ultimately just a fancy phrase that refers to the Python program that you download; again, see Appendix A.) You can write your programs in a word processor if you really want, but you have to save them as text-only files, or they will not work as intended. Documents written in word processors have additional unseen characters that give the files their formatting, and when you attempt to convert a program written in such a file to machine code, as discussed earlier in the chapter, it will not work because of these extra unseen characters.

Note

Unlike word processors, your editor will not wrap the end of a line down to the subsequent line. It’s important that programming instructions (called statements) remain separate and stay on their own lines in many cases. Even if a programming language allows multiple program statements per line, you’ll find that your programs are more readable and easier to debug if you keep your statements one per line. Sometimes, a single statement can get lengthy, and you may span long statements over two or three lines, but rarely would you want multiple statements to appear on the same line.

Also, while many programming languages ultimately do not care about spaces and line breaks, the spacing is very important to how a Python program is written. If you follow the spacing in the programs as written in this book, you will be fine, and you will soon find yourself following the pattern automatically.

Clarifying Comments

The program presented in Figure 1.2 has not only program statements but also some lines that do not do anything when the program is run; however, these lines have great value to anyone reading your code. These lines, which start with a pound sign (#), are known as comments. Python ignores all text to the right of the pound sign. As soon as you press Return, Python starts paying attention to the code again. So if you want to keep commenting, you need to start the next line with a fresh pound sign. Consider an example:

# The next five lines ask users for their favorite
# movie and flavor of gelato

In this example, if you left off the pound signs, Python would assume that you were either typing The or calling a function named The, and you might not get the results you were expecting.

All languages support comments, which are also called remarks, although some languages use slashes instead. Although you’ll find many comments in programs, and you should put many comments in the programs you write, comments are not for the interpreter or for the computer. Comments are for people. In Python, for example, the interpreter ignores all text to the right of pound sign. The computer knows that comments are for you and not for it.

Reasons for Comments

Comments help produce more understandable program listings. The programming industry considers including comments to be one of the most important good programming habits you can develop. Here are common reasons programmers put comments in their programs:

Image Comments can identify programmers. If you develop programs with others or write programs for a company, you should put your name and contact information in comments at the top of your programs. Later, anyone who has a question about the program or wants you to change the program will know that you wrote the program and will be able to contact you.

Image Before a section of tricky code, you can use comments to include your explanation of the code’s purpose. Later, if you or someone else needs to change the program, the change will be easier; reading the comments is much simpler than trying to figure out the goals of the tricky code from uncommented code.

Placement of Comments

When you use the pound sign (#), a comment can appear on the same line as code. The following code shows comments to the right of lines of other program instructions:

if hours > 12:              # Test the hour for AM/PM indicator
   hours = hours - 12   # Convert 24-hour time to 12-hour
   amOrPm$ = " PM"   # Set indicator that will print

Tip

While most programming languages are free-form, meaning that you can indent lines and add as many spaces and blank lines as you like, Python does have some rules around indentation and whitespace (extra spaces and lines in code). Following these rules makes your program more readable. In Hour 7, you’ll learn how to use whitespace to improve your programs’ readability by separating one program section from another, thereby making it easier for programmers to understand your code.

Sure, as a programmer, you will often understand code without the need to put a remark to the right of each line. But at the time you write a program, the program is clearest to you. When you later go back to edit a program, what may have been clear before may no longer be so clear because time has passed. A few comments will go a long way toward reminding you of your original intent.

However, do not overdo comments. Some comments are redundant, as the following shows:

print("Martha")   # Prints the word Martha

Such a comment is not helpful and serves only to cloud an already-understandable instruction. Don’t overuse comments but do use them generously when needed to clarify your code.

Entering Your Own Program

You’re now ready to type and run your own simple program from scratch. The goal here is to get you used to using the editor or IDE you selected in Appendix A.

Summary

Now that you know a bit more about the computer industry as a whole, you have a better idea of where programmers fit into the picture. Computers can do nothing without programs, and programmers are responsible for providing those programs.

You have already gotten a taste of programming this hour by typing your first Python program and viewing the results. As you saw by typing your own program into an editor, entering and running a code is not painful at all. As a matter of fact, the quick feedback that programming offers is a rewarding experience. Programmers often like their profession very much because they can see the results of their work quickly.

Q&A

Q. When I finish writing a program, is my job finished?

A. It is said that a program is written once and modified many times. Throughout this 24-hour tutorial, you will learn the importance of maintaining a program after it is written. As businesses change and computing environments improve, the programs that people use must improve as well. Companies provide upgrades to software as new features are needed. The programs that you write today will have to change in the future to keep up with the competition as well as with new features that your users require.

Q. Can I enter other programming language listings in my editor as well?

A. The Jupyter Notebook, suggested in Appendix A, is specific to Python. If you chose to use a text editor, you can write programs in other programming languages, such as C, C++, and Java, in your text editor. However, you would need a compiler or an interpreter (depending on the language) to convert the programming language’s code to machine language. A machine language program is your program’s instructions compiled to a language your computer can understand. You can also find IDEs specific to those languages.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What is the difference between data and information?

2. What is a program?

3. What is a programming language?

4. True or false: Computers never make mistakes.

5. Why should people not fear computers replacing their jobs?

6. What do programmers use editors for?

7. What does IDE stand for?

8. True or false: There’s no problem writing your programs in a typical word-processing program.

9. Tweak the program in Listing 1.2 so that the Name is set to the name of someone else you know.

Answers

1. Data consists of raw facts and figures, and information is processed data that has more meaning.

2. A program is a set of detailed instructions that tells the computer what to do.

3. A programming language is a set of commands and grammar rules with which you write programs that give computers instructions.

4. False. A computer might make a mistake, but it’s rare that it does so. In the vast majority of cases where a computer is blamed, a person entered bad data or typed a bad program.

5. Computers increase jobs rather than replacing them. The information industry has had a large impact on the economic growth of the past several decades.

6. Programmers use editors to type programs into the computer.

7. Integrated development environment.

8. False. The default method of saving files in word processors adds formatting codes that generate errors when you try to run your program. You can still use a word processor, but you must always remember to save your files as plain text.

9. Here is one possible solution:

'''
Teach Yourself Beginning Programming in 24 Hours
Listing 1.2
'''

ProgLang = "Python"
Hours = 24
Name = "Maggie" #If you want you can change this to your name!

print("We are learning programming basics in what language?")
print(ProgLang,"!")
print(Name,"will soon be programming after", Hours, "Hours!")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.141.202