Easy Python 3 - Lesson 2

7/19/2020

To Do!

Recap

Python logo.

At the beginning of each lesson I will recap the previous lesson. If you need help with any of the word meanings, go back to Lesson 1 and look for words in bold. On first use of a term in each lesson, it will be bold and the meaning will appear as a tool-tip when holding your cursor over the word. After that I will use the term normally. It is important to gain understanding of the words and terms used in programming. It will help in understanding not only the how of programming, but also in understanding the why of programming. A wise teacher once told me that knowing how to do something is great. But, knowing why you do it that way makes it much more permanent in your memory.

In the Lesson 1, we used five different methods to the output "Hello, world!" First, we simply used the print() function to output the string literal, "Hello, world!" Second, we used an assignment operator to assign the same string to a variable and then printed the variable. Third, we used the input() function to ask us a question and then assign the answer as a string to the variable and then print it. Fourth, we concatenated a string literal to a string variable. And finally, we used escaped characters to print the sting on two lines. Along the way, we learned a few of the features in CodeSkulptor that we will continue to use in these lessons.

Comments

You may want to say something in your code that can be read by humans but not executed by the computer like code. Comments Text in programs readable by humans. Python ignores them. are used for this. Comment lines begin with the # symbol and are not read by Python. Comments are a good way to explain your code and should be used often. If you are a student, you should be starting your programs with four comment lines that state: Name, Class, Assignment, and Date - just as you would for an assignment in any class.

Using Comments

1. Open CodeSkulptor.

2. Begin with the four comment lines for your student information.

3. Next, add a blank line and follow it with three assignment statements and three print statements, as shown below.

4. Add comments to separate blocks of code by what it does. Also, let's add an empty print() statement after every printing block of code. This will make our output easier to read. Your code should look like this:

#Your Name
#Easy Python
#Lesson 2
#Date

#Assigning values to variables
x="words"
y=1
z=2.1

#Printing variable values
print(x)
print(y)
print(z)
print()

5. Run your program, then click  New URL  . Drag the URL to your bookmarks for this class and rename it Lesson 2.

  Adding blank lines and commenting blocks of code that contain similar content will help make your code more understandable.

Note: By using CodeSkulptor to save URL's of your work, and commenting the code you write, your programs (for each lesson) can be used as your notes. As you work through each lesson, add new concepts in a comment above the code, then add both below the previous code. This will keep all the code for each lesson in its own file.

The output of the code above should be:

words
1
2.1

Data Types

Let's try to gain some understanding of Python's data types The type of data and use of a Python object. by taking them a few at a time. We can add more as we progress. We have been using the print function to output the letters, "Hello, world!" which is a string or str data type, which we have already learned. Two more data types we will often use are, integersA whole number, positive, negative, or zero of any length that is not a decimal. int and floatsA positive or negative decimal number. float. Python has more data types, but for now let's concentrate on using these three.

Data Type Type Name Definition
Text str string
Numeric int integer
Numeric float decimal

We can use the type() function to return the data type of Python objects.

Data Types

1. Below the previous code in this lesson add the following:

#Using the print and type functions to output each variable type.
print(type(x))
print(type(y))
print(type(z))
print()

2. Clicking  Run  should give you the following output:

<class 'str'>
<class 'int'>
<class 'float'>

  Remember that the output above will appear below the previous code covered in this lesson.

Everything in Python is considered an object and all objects have identity (name), type, and value. In the example code, the variable named x is a data type of string with a value of "words." The variable with the identity y is a type of integer with a value of 1. Python executes code from top to bottom and from right to left. So, if you were state one of these lines in plain English, it would be something like, "Take the value of x, find its type and display it."

Functions

We previously talked a little about functions and parameters. One of the things functions do is allow us to reuse blocks of code. Since functions are such an important principle in programming, let's look a little closer.

As defined in the first lesson, a function is a named block of reusable code that performs a specific task. So far we have been using a few of them: print(), input(), and type() are all functions. Python has many functions built into it and you can also create your own. We will learn much more about functions, but for now, let's try writing the Hello, world! program, by creating our own function that uses two of Python's built-in functions we have learned. To create a function we start by using the keyword A reserved word that can't be used as an ordinary identifier. called def, which is a reserved word used in Python for defining a function. Why don't we go ahead and write this code and then we can cover what it means.

Hello, world! Using a Function

1. Below the previous code in this lesson add the following:

#A function that prints "Hello, world!"
def greeting(a, b):
     print(a + ", " + b + "!")

2. Try clicking  Run  . What happens? The output has not changed because we must call the some other place in our code.

3. Below your function enter a blank line and the following code:

#Calling the function
greeting("Hello","world")

4. When we click  Run  we should get the following new output added below the previous output from this lesson:

Hello, world!

OK, that was a lot! Let's go over what we just did. We'll take it word by word.

We used def to define or create a function. We named our new function greeting, which is descriptive of what the function does. Next, we used opening and closing parenthesis () which are necessary for all functions and contain the parameters. Sometimes the parenthesis can be empty. Here we used a, b, which are two variables. Parameters are always separated by commas. Last in the function definition line is a colon :. Next we press the Enter key to go to the next line. Notice that CodeSkulptor automatically indents the next line. A good programming IDE (Integrated Development Environment) will always take care of most formatting tasks for you.

Note: Indentation is important in Python and is used by the Python interpreter A program that reads and executes code. to distinguish blocks of code that belong together. If you need to manually indent, use a single TAB keystroke.

Now our function definition line is complete and we are at the next indented line. Here is the code that actually does the function's task. (Remember - functions carry out a task.) This line looks a little cryptic, doesn't it?
print(a + ", " + b + "!")
I see the print() function and I see the two variables a and b. But what's that other stuff?

As we did in the first lesson, we use concatenation to connect our variables and two strings necessary for punctuation. Expressing this line in plain English, sometimes called pseudo-code, it would be something like:
print the contents of variable a then add a , and a then add the contents of variable b and add !.

Using these principles, let's make our function a little more useful. We named it greeting, but we are kind of limited to Hello, world! at this point. Let's see if we can write something that allows the user to have a greeting of their choice. We can add a couple of input() functions that ask the user for a greeting and a person to greet and store that information in two variables, then use the variable contents as arguments An argument is the value that is sent to a function when it is called. for our function.

Function with user input

1. As always, below the previous code in this lesson add the following:

#Getting a user input 
greet = input("Enter a greeting: ")
who = input("Enter a name: ")

2. After these user inputs, enter a blank line and the following code:

#Calling the function with the input variables as arguments
greeting(greet, who)

3. If our code is correct, when we click  Run  we should get the a prompt to enter a greeting and another to enter a name. After the second prompt, we should have the following in the Output window: (I entered "Hi" and "Mom")

Hi, Mom!

Notice that we were able to modify the results of the of the function without changing the function itself. This is an easy example of how functions can enhance and simplify our programming skills. Functions also give us the ability to reuse code for repetitious tasks and we'll be using them every program we write. There are 68 built-in, predefined functions in Python. There are also many modules containing related functions that can be accessed by using the import keyword, followed by the module name. So basically, we will be using functions in Python in three ways:

  1. Built-in
  2. Imported
  3. User defined

Lesson Walk-through

Click here for all the code in this lesson.


  Answer each Quick Check question then click the question text to see the correct answer.

Quick Check - Answer the question, then click the question text to see the correct answer.

Text that is not executed by Python but is readable by a human is called a ___________.

comment

A comment line always begins with what symbol?

#

Python organizes objects in categories called ____________.

data types

The data type for a string is ______.

str

The variables used by a function which are inside the parenthisis are called ________.

parameters

A reserved word that can't be used as an ordinary identifier is a ________.

keyword or reserved word

To create a function, start with the keyword ________.

def

The initial line of a function definition always ends with a ________.

colon, :

The Python language uses indentation to distuinguish related blocks of code. True or False?

True

  Based on what you have learned, write a solution to each problem. My answers are only example solutions.

On Your Own

Write a program that ask the user for a word, an integer, and a decimal number. Store the values in variables. Show each user response in the following format:
You entered the number 3 which is:
<class 'int'>
This example shows the user entered 3 for an integer.

#Getting user input
word=input("Enter a word: ")
number=input("Enter an integer: ")
decimal=input("Enter a decimal number: ")

#printing user responses and Python types
print("You entered the word " + word + " which is a type of:")
print(type(word))
print()
print("You entered the number " + number + " which is a type of:")
print(type(number))
print()
print("You entered the decimal " + decimal + " which is a type of:")
print(type(decimal))
print()

Using only the keys on your keyboard, create an emoji of some kind. It can be an animal, and object or a face. It must render in the output pane as at least 3 lines, but it can only use the one print function and one line of code. You will need to use the escape characters necessary to write this.

print("\t(\\__/)\n\t(=`.`)\n\t(_(\")(\")")

Write a simple Mad Libs game where you insert the answers to questions into a silly story. Use at least 4 items - an exclamation, an adverb, a noun, and an adjective. Then fit them into a nonsensical story.

print("***Silly Story***")
excl=input("Give me an exclamatory word.")
adv=input("Give me an adverb.")
noun=input("Give me a noun.")
adj=input("Give me an adjective.")
print("All together we shouted "+excl+" "+adv+" as we \nlooked at the "+noun+" with its "+adj+" eyes.")

Acknowledgments



 

This article is a lesson from the high school course Introduction to Computer Science with Python 3. Thanks for viewing. Please check out my other articles on education and technology. I welcome any comments!


Comments »

© 2020 - KRobbins.com

If attribution for any resource used on this or any page on krobbins.com is incorrect or missing, please check the about page. If there is still an error, please contact me to correct it.