Introduction

Welcome to my Python Course! 

Python is a general-purpose computer programming language.
This course is suitable for both Python 2 and Python 3.

Related Courses:

Download Python

To run Python code, you will need one of these programs:

For terminal only: Apple Mac OS X, Microsoft Windows, Linux/UNIX

pycharm
PyCharm, a popular Python editor

Run Python code

A python program should be save as a file with a .py extension.
Try this code:

print("Hello World!")
print("This is a Python program.")

Expected output:

Hello World!
This is a Python program

If you are using the interpreter use:

python program.py

Python strings

python-string
a string, series of characters
A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Courses:

String input and output

To output text (string) to the screen:

s = "hello world"
print(s)

To get text from keyboard:

name = input("Enter name: ")
print(name)

If you use an old Python version (2.x), you need to use:

name = raw_input("Enter name: ")
print(name)

To test your version:
python –version

String Comparison

To test if two strings are equal use the equality operator (==).

#!/usr/bin/python
 
sentence = "The cat is brown"
q = "cat"
 
if q == sentence:
    print('strings equal')

To test if two strings are not equal use the inequality operator (!=)

#!/usr/bin/python
 
sentence = "The cat is brown"
q = "cat"
 
if q != sentence:
    print('strings equal')

String Slices (part 2)

A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Courses:

String Index

Python indexes the characters of a string, every index is associated with a unique character. For instance, the characters in the string ‘python’ have indices:

String
String numbering

Characters in string

The 0th index is used for the first character of a string. Try the following:

#!/usr/bin/python
 
s = "Hello Python"
print(s)      # prints whole string
print(s[0])   # prints "H"
print(s[1]) # prints "e"

String Slicing

Given a string s, the syntax for a slice is:

s[ startIndex : pastIndex ]

The startIndex is the start index of the string. pastIndex is one past the end of the slice.

If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:

#!/usr/bin/python
 
s = "Hello Python"
print(s[0:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:])  # prints "Python"

Python variables

python-variables
Variables in Python (x,y,z). They can be used later in the program
Variables can hold numbers that you can use one or more times.

Numbers can be of one of these datatypes:

  • integer (1,2,3,4)
  • float (numbers behind the dot)
  • boolean (True or False)

Related courses

Numeric variables example

Example of numeric variables:

x = 1
y = 1.234
z = True

You can output them to the screen using the print() function.

x = 1
y = 1.234
z = True
 
print(x)
print(y)
print(z)

Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).

#!/usr/bin/env python
 
x = 3
y = 8
 
sum = x + y
 
print(sum)

More mathematical operations

User input

Python 3
Use the input() function to get text input, convert to a number using int() or float().

#!/usr/bin/env python
 
x = int(input("Enter x:"))
y = int(input("Enter y:"))
 
sum = x + y
print(sum)

Python 2 (old version)
You can also ask the user for input using the raw_input function:

#!/usr/bin/env python
 
x = int(raw_input("Enter x:"))
y = int(raw_input("Enter y:"))
 
sum = x + y
print(sum)

Python lists

Lists is a sequence and a basic data structure.   A list may contain strings (text) and numbers.  A list is similar to an array in other programming languages, but has additional functionality.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

Python List

We define lists with brackets []. To access the data, these same brackets are used.
Example list usage:

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
print(l[0])  # print first element
print(l[1])  # prints second element

Add/remove

We can use the functions append() and remove() to manipulate the list.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)                # prints all elements
l.append("Victoria")   # add element.
print(l)                # print all elements
l.remove("Derp")       # remove element.
l.remove("Drake")      # remove element.
print(l)               # print all elements.

Sort list

We can sort the list using the sort() function.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
print(l)     # prints all elements

If you want to have the list in descending order, simply use the reverse() function.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
l.reverse() # reverse order.
print(l)     # prints all elements

If statements

In Python you can define conditional statements, known as if-statements.
A block of code is executed if certain conditions are met.

Related Courses:

If statements

Consider this application, it executes either the first or second code depending on the value of x.

 
#!/usr/bin/python
 
x = 3
if x < 10:
   print("x smaller than 10")
else:
   print("x is bigger than 10 or equal")

If you set x to be larger than 10, it will execute the second code block.   We use indentation (4 spaces) to define the blocks.

A little game:
A variable may not always be defined by the user, consider this little game:

age = 24
 
print "Guess my age, you have 1 chances!"
guess = int(raw_input("Guess: "))
 
if guess != age:
    print("Wrong!")
else:
    print("Correct")

Conditional operators

A word on conditional operators

OperatorDescription
!=not equal
==equals
>greater than
<smaller than

Do not confuse the assignment operator (=) with the equals operator (==).

Nesting

The most straightforward way to do multiple conditions is nesting:

a = 12 
b = 33
 
if a > 10:
    if b > 20:
        print("Good")

This can quickly become difficult to read, consider combining 4 or 6 conditions.  Luckily Python has a solution for this, we can combine conditions using the and keyword.

guess = 24
if guess > 10 and guess < 20:
    print("In range")
else:
    print("Out of range")

Sometimes you may want to use the or operator.

Posts navigation

1 2 3 4 5 6 7