Practical Python Programming 01_02_Hello_world

catalogue | Previous section (1.1 Python) | Next section (1.3 digits)

1.2 first procedure

This section discusses the basics of how to create a program, run the interpreter, and debug.

Run Python

Python programs always run in the interpreter.

An interpreter is a "console based" application that is usually launched from a command line shell.

python3
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Experienced programmers usually have no problem using the interpreter in this way, but it is not so friendly for beginners. You may use an environment that provides different interfaces for Python, but learning how to run Python terminals is still a necessary skill.

Interactive mode

When you start Python, you can enter an interactive mode, in which you can program experiments.

If you enter the code, it will run immediately. There are no processes such as edit/compile/run/debug.

>>> print('hello world')
hello world
>>> 37*42
1554
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>>

This is called "read evaluate output loop", It is very useful for code debugging and exploration.

Pause: if you don't know how to interact with Python, stop what you're doing, and then figure out how to interact with Python. If you are using an integrated development environment (IDE), it may be hidden behind a menu option or other window. Many parts of this course assume that you can interact with the interpreter.

Let's take a closer look at the elements of REPL:

  • >>>The prompt is used to start a new statement.
  • ... The prompt is used to continue a statement, enter a blank line to end all input, and run the entered code.

... The prompt may or may not be displayed, depending on the environment in which it is used. For this course, you will The prompt is blank to cut and paste the sample code.

Underline_ Save the final result.

>>> 37 * 42
1554
>>> _ * 2
3108
>>> _ + 50
3158
>>>

Only in interactive mode (meaning underline saves the final result), never use this method in your program.

Create program

Write the program py file.

# hello.py
print('hello world')

You can use your favorite text editor to create these py file.

Run program

To execute the program, use the Python command to execute it in the terminal. For example, in the command line of Unix system, a Python program is executed as follows:

For example, execute the program in the command line of Unix system:

bash % python hello.py
hello world
bash %

Alternatively, execute a Python program from the Windows shell:

C:\SomeFolder>hello.py
hello world

C:\SomeFolder>c:\python36\python hello.py
hello world

Note: on Windows systems, you may need to specify the full path of the Python interpreter, such as c:\python36\python. However, if Python is installed in the usual way, you may only need to enter the program file name, such as hello py.

Sample program

Let's solve the following problems:

One morning, you go out and put a dollar bill on the sidewalk next to the Sears building in Chicago. Every day since then, you have put twice as much money as the previous day. How long does it take for this stack of notes to exceed the height of the tower.

Here's the answer:

# sears.py
bill_thickness = 0.11 * 0.001 # Meters (0.11 mm)
sears_height = 442 # Height (meters)
num_bills = 1
day = 1

while num_bills * bill_thickness < sears_height:
    print(day, num_bills, num_bills * bill_thickness)
    day = day + 1
    num_bills = num_bills * 2

print('Number of days', day)
print('Number of bills', num_bills)
print('Final height', num_bills * bill_thickness)

When executing Sears Py program, you will get the following output:

bash % python3 sears.py
1 1 0.00011
2 2 0.00022
3 4 0.00044
4 8 0.00088
5 16 0.00176
6 32 0.00352
...
21 1048576 115.34336
22 2097152 230.68672
Number of days 23 
Number of bills 4194304 
Final height 461.37344

Using this program as a guide, you can learn many important core concepts about Python.

sentence

A Python program consists of a series of statements.

a = 3 + 4
b = a * 2
print(b)

Each statement terminates with a newline character. Statements are executed one after another until the control flow reaches the end of the file.

notes

Comments are text that will not be executed by the interpreter.

a = 3 + 4
# This is a comment
b = a * 2
print(b)

A comment is indicated by a # sign and extends to the end of the line.

variable

A variable is the name of a value. You can use letters from a to z (both lowercase and uppercase) or underline_ Symbolic representation. Numbers can also be part of variable names, except for the first character.

height = 442 # valid
_height = 442 # valid
height2 = 442 # valid
2height = 442 # invalid

type

Variables do not need to be declared with the type of value. Type is associated with the value on the right, not the variable name.

height = 442           # An integer
height = 442.0         # Floating point
height = 'Really tall' # A string

Python is a dynamic language. When the program executes, the perceived "type" of the variable may change, depending on the current value assigned to the variable.

Case sensitive

The Python language is case sensitive (i.e., case sensitive), and uppercase and lowercase letters are considered different letters. These are different variables:

name = 'Jake'
Name = 'Elwood'
NAME = 'Guido'

Python's own statements are always lowercase:

while x < 0:   # OK
WHILE x < 0:   # ERROR

loop

The while statement executes a loop:

while num_bills * bill_thickness < sears_height:
    print(day, num_bills, num_bills * bill_thickness)
    day = day + 1
    num_bills = num_bills * 2

print('Number of days', day)

As long as the value of the expression after while is true, the indented statement under while will be executed.

indent

Indents are used to represent groups of statements that are put together. Consider the previous example:

while num_bills * bill_thickness < sears_height:
    print(day, num_bills, num_bills * bill_thickness)
    day = day + 1
    num_bills = num_bills * 2

print('Number of days', day)

Indent groups the following statements into a repeating operation:

    print(day, num_bills, num_bills * bill_thickness)
    day = day + 1
    num_bills = num_bills * 2

Because the print() statement at the end (i.e. print('Number of days', day)) is not indented, it does not belong to a loop. Blank lines are only for readability and do not affect the execution of the program.

Best practices for indenting

  • Use spaces instead of tabs.
  • Use four spaces per level.
  • Use an editor that supports Python.

The only requirement of Python is that the indents in the same code block must be consistent. For example, the following indentation is wrong:

while num_bills * bill_thickness < sears_height:
    print(day, num_bills, num_bills * bill_thickness)
        day = day + 1 # ERROR
    num_bills = num_bills * 2

Conditional statement

The if statement is used to execute a condition:

if a > b:
    print('Computer says no')
else:
    print('Computer says yes')

To check multiple conditions, you can use elif to add additional checks.

if a > b:
    print('Computer says no')
elif a == b:
    print('Computer says yes')
else:
    print('Computer says maybe')

output

The print function outputs the passed in parameter value as a line of text.

print('Hello world!') # Prints the text 'Hello world!'

You can also output variables. The output text will be the value of the variable, not the name of the variable.

x = 100
print(x) # Prints the text '100'

If more than two values are passed to the print function, they are separated by spaces when output.

name = 'Jake'
print('My name is', name) # Print the text 'My name is Jake'

The print() function always puts the newline character last.

print('Hello')
print('My name is', 'Jake')

The above code will output the following contents:

Hello
My name is Jake

Additional line breaks can be suppressed:

print('Hello', end=' ')
print('My name is', 'Jake')

The above code will output the following:

Hello My name is Jake

User input

To read a line of typed user input, you can use the input() function:

name = input('Enter your name:')
print('Your name is', name)

The input() function outputs a prompt to the user and returns their response.

This is very useful for a short program, learning exercise or simple debugging.

However, this has not been widely used in practical procedures.

pass statement

Sometimes you need to specify an empty code block, you can use the pass keyword.

if a > b:
    pass
else:
    print('Computer says false')

The pass statement, also known as the "no action" statement, does nothing. It is used as a placeholder for statements and may be added later.

exercises

This is the first set of exercises to create a python file and run it. From now on, assume that the file you are editing is located in the practical Python / work / directory. To help you find the right location, many empty startup files with the right file names have been created. Please find the work / bounce used in the first exercise Py file.

Exercise 1.5: bouncing ball

A rubber ball falls from a place 100 meters high and bounces to 3 / 5 of its original height every time it hits the ground. Write a program bounce Py, output a table showing the height of the first 10 rebounds.

The table generated by the program is roughly like the following:

1 60.0
2 36.0
3 21.599999999999998
4 12.959999999999999
5 7.775999999999999
6 4.6655999999999995
7 2.7993599999999996
8 1.6796159999999998
9 1.0077695999999998
10 0.6046617599999998

Note: if you use the round () function, you can make the output a little simpler. Try using the round() function to round the output to four decimal places.

1 60.0
2 36.0
3 21.6
4 12.96
5 7.776
6 4.6656
7 2.7994
8 1.6796
9 1.0078
10 0.6047

Exercise 1.6: debugging

The following code snippet contains the code from the Sears building problem, which also has a bug:

# sears.py

bill_thickness = 0.11 * 0.001    # Meters (0.11 mm)
sears_height   = 442             # Height (meters)
num_bills      = 1
day            = 1

while num_bills * bill_thickness < sears_height:
    print(day, num_bills, num_bills * bill_thickness)
    day = days + 1
    num_bills = num_bills * 2

print('Number of days', day)
print('Number of bills', num_bills)
print('Final height', num_bills * bill_thickness)

Copy and paste the code shown above into a file named Sears In the new program of py. When executing Sears Py, you will receive an error message that causes the program to crash. The error message is as follows:

Traceback (most recent call last):
  File "sears.py", line 10, in <module>
    day = days + 1
NameError: name 'days' is not defined

Reading error messages is an important part of Python code. If the program crashes, the last line of the backtracking message is the actual reason why the program crashed. Above this (NameError: name 'days' is not defined), you should see the source code fragment (day = days + 1), the recognizable file name (sears.py) and the line number of the error code (line 10).

  • Which line is wrong?
  • What is the mistake?
  • Resolve the error.
  • Successfully run the program. Run the program successfully

catalogue | Previous section (1.1 Python) | Next section (1.3 digits)

Tags: Python

Posted by CBR on Tue, 19 Apr 2022 09:27:20 +0930