nlouie-intro-to-python-atbs

intro to programming in python

View the Project on GitHub nlouie/nlouie-intro-to-python-atbs

Python Programming for Beginners Demo 0 - Python Basics

print("Hello world!")
Hello world!

Intro

Other helpful resources:

What is programming?

How does it work?

Example 1 - Looking for someone in a grocery store


while (parentNotFound) {
    foreach (aisle in aisles) {
        if (parentIsInAisle) {
            walkTowardsParent();
        }
    }
}

Programming Languages

Download Python 3.8

Windows

http://python.org/

MacOS

From your terminal…


$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
$ brew install python3

Ubuntu


$ sudo apt-get install python3

What is Python?

Python is a programming language (with syntax rules for writing what is considered valid Python code) and the Python interpreter software that reads source code (written in the Python language) and performs its instructions. You can download the Python interpreter for free at https://python.org/, and there are versions for Linux, macOS, and Windows.

The name Python comes from the surreal British comedy group Monty Python, not from the snake. Python programmers are affectionately called Pythonistas, and both Monty Python and serpentine references usually pepper Python tutorials and documentation.

I encourage you to type into the interactive shell, also called the REPL (Read-Evaluate-Print Loop), which lets you run (or execute) Python instructions one at a time and instantly shows you the results.

Using the interactive shell is great for learning what basic Python instructions do, so give it a try as you follow along. You’ll remember the things you do much better than the things you only read.

Getting started with IDLE

Open IDLE (should be installed with Python). An interactive shell will come up. Create a new file, and name it test.py You can use this python file to write python programs. Run it from the menu bar, or pressing F5

IDLE Documentation

Running Python on the Command Line (Optional)

Download a text editor, like Atom


$ python
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Or run a python file


$ python file.py

More info

Online Interactive Python

Try Python online without downloading

https://repl.it/

Programming Basics

Statements, Printing, Comments

print('I am a statement!') # I am a line comment
# print('I am also a statement!') 
print('Player number:', 1)

'''
I am a block comment 
'''
I am a statement!
Player number: 1





'\nI am a block comment \n'

Operators and expressions

In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate (that is, reduce) down to a single value. That means you can use expressions anywhere in Python code that you could also use a value.


Operator Operation Example Evaluates to
** exponent 2 ** 3 8
% Modulus/remainder 22 % 8 6
// Integer division/floored quotient 22 // 8 2
/ Division 22 / 8 2.75
* Multiplication 3 * 5 15
- Subtraction 5 - 2 3
+ Addition 2 + 2 4

1 + 1
2
2 * 6
12
5 - 10
-5
(5 - 1) * ((7 + 1) / (3 - 1)) # PEMDAS
16.0
23 / 7
3.2857142857142856
23 // 7
3

Modulus

23 % 7
2
10 ** 2
100

Error Messages

8 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-29-340e47a3b5ce> in <module>
----> 1 8 / 0


ZeroDivisionError: division by zero

The Integer, Floating-Point, and String Data Types

Remember that expressions are just values combined with operators, and they always evaluate down to a single value. A data type is a category for values, and every value belongs to exactly one data type.

Data type Example
String “hello”, ‘hi’, ‘a’, ‘64 cats’
Integer -2, -1, 0, 1, 2, 3, 4, 5
Float -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25
# strings
print('hello world')
hello world

String Concatenation and Replication

The meaning of an operator may change based on the data types of the values next to it. For example, + is the addition operator when it operates on two integers or floating-point values. However, when + is used on two string values, it joins the strings as the string concatenation operator.

'alice' + 'bob'
'alicebob'
# Mixing data types can crash your program or cause unexpected behavior
'alice' + 2
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-32-281b897eb5c9> in <module>
      1 # Mixing data types can crash your program or cause unexpected behavior
----> 2 'alice' + 2


TypeError: can only concatenate str (not "int") to str
'Alice' * 5
'AliceAliceAliceAliceAlice'
'Alice' * 5.0
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-34-43325524c797> in <module>
----> 1 'Alice' * 5.0


TypeError: can't multiply sequence by non-int of type 'float'

Storing Values in Variables

spam = 42
spam
42
x = 0
y = 1
x + y
1
first_name = "Biggie"
last_name = "Smalls"
full_name = first_name + " " + last_name # string concatenation
print(full_name)
Biggie Smalls
print(full_name)
Biggie Smalls
full_name = "Ghostface Killa"
print(full_name)
Ghostface Killa

Variable Names

Though you can name your variables almost anything, Python does have some naming restrictions. You can name a variable anything as long as it obeys the following three rules:


Valid variable names Invalid variable names
current_balance current-balance (hyphens are not allowed)
currentBalance current balance (spaces are not allowed)
account4 4account (can’t begin with a number)
_42 42 (can’t begin with a number)
TOTAL_SUM TOTAL_\$UM (special characters like $ are not allowed)
hello ‘hello’ (special characters like ‘ are not allowed)

Creating your first program


# This program says hello and asks for my name.

print('Hello, world!')
print('What is your name?')    # ask for their name

my_name = input()
print('It is good to meet you, ' + my_name)

print('The length of your name is:')
print(len(my_name))

print('What is your age?')    # ask for their age
my_age = input()
print('You will be ' + str(int(my_age) + 1) + ' in a year.')

Optional example, running from command line


# find where you saved your python file..such as your Desktop
$ cd ~/Desktop
$ python demo0.py

Dissecting Your Program

The print() Function

print('Hello, world!')
Hello, world!

The input() Function

my_name = input()
print('It is good to meet you ' + my_name)
Al
It is good to meet you Al

Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in my_name, then this expression evaluates to 'It is good to meet you, Al'. This single string value is then passed to print(), which prints it on the screen.

The len() Function

You can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string.

len("hello")
5
len("The quick brown fox jumped over the lazy dog")
44
len('')
0
len("")
0
print('I am ' + 29 + ' years old.')
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-46-40e8f0b932d8> in <module>
----> 1 print('I am ' + 29 + ' years old.')


TypeError: can only concatenate str (not "int") to str

The print() function isn’t causing that error, but rather it’s the expression you tried to pass to print(). You get the same error message if you type the expression into the interactive shell on its own.

'I am ' + 29 + ' years old.'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-47-b2e1590c4132> in <module>
----> 1 'I am ' + 29 + ' years old.'


TypeError: can only concatenate str (not "int") to str

The str(), int(), and float() Functions

str(29)
'29'
print('I am ' + str(29) + ' years old.')
I am 29 years old.
str(0)
'0'
str(-3.14)
'-3.14'
int('42')
42
int('-99')
-99
int(1.25)
1
float(3.14)
3.14
float(10)
10.0
spam = input()
spam
101





'101'

The value stored inside spam isn’t the integer 101 but the string ‘101’. If you want to do math using the value in spam, use the int() function to get the integer form of spam and then store this as the new value in spam.

spam = int(spam)
spam
101

Now you should be able to treat the spam variable as an integer instead of a string.

spam
101

Note that if you pass a value to int() that it cannot evaluate as an integer, Python will display an error message.

int('99.99')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-60-7e09e10be494> in <module>
----> 1 int('99.99')


ValueError: invalid literal for int() with base 10: '99.99'
int('twelve')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-61-bcdccb17a8a6> in <module>
----> 1 int('twelve')


ValueError: invalid literal for int() with base 10: 'twelve'

The int() function is also useful if you need to round a floating-point number down.

int(7.7)
7
int(7.7) + 1
8

TEXT AND NUMBER EQUIVALENCE

42 == '42'
False
42 == 42.0
True
42.0 == 0042.000
True

Summary

You can compute expressions with a calculator or enter string concatenations with a word processor. You can even do string replication easily by copying and pasting text. But expressions, and their component values—operators, variables, and function calls—are the basic building blocks that make programs. Once you know how to handle these elements, you will be able to instruct Python to operate on large amounts of data for you.

It is good to remember the different types of operators (+,-, *, /, //, %, and ** for math operations, and + and * for string operations) and the three data types (integers, floating-point numbers, and strings) introduced in this chapter.

I introduced a few different functions as well. The print() and input() functions handle simple text output (to the screen) and input (from the keyboard). The len() function takes a string and evaluates to an int of the number of characters in the string. The str(), int(), and float() functions will evaluate to the string, integer, or floating-point number form of the value they are passed.

In the next chapter, you’ll learn how to tell Python to make intelligent decisions about what code to run, what code to skip, and what code to repeat based on the values it has. This is known as flow control, and it allows you to write programs that make intelligent decisions.

Questions?

Feedback?

Practice Questions

  1. Which of the following are operators, and which are values?

*
'hello'
-88.8
-
/
+
5

  1. Which of the following is a variable, and which is a string?

spam
'spam'

  1. Name three data types.

  2. What is an expression made up of? What do all expressions do?

  3. This module introduced assignment statements, like spam = 10. What is the difference between an expression and a statement?

  4. What does the variable bacon contain after the following code runs?


bacon = 20
bacon + 1

  1. What should the following two expressions evaluate to?

'spam' + 'spamspam'
'spam' * 3

  1. Why is eggs a valid variable name while 100 is invalid?

  2. What three functions can be used to get the integer, floating-point number, or string version of a value?

  3. Why does this expression cause an error? How can you fix it?


'I ate ' + 99 + ' burritos.'

Extra credit: Search online for the Python documentation for the len() function. It will be on a web page titled “Built-in Functions.” Skim the list of other functions Python has, look up what the round() function does, and experiment with it in the interactive shell.

Credits

https://automatetheboringstuff.com/