NLC Intro To Python For Newbies
NLC Intro To Python For Newbies
TO
PYTHON
WHAT IS PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991
INTERACTIVE: allows the creator to make changes to the program while it is already running
INTERPRETED: Code is written and directly executed by an interpreter. Allow you to type one command at a time and
see results
OBJECT ORIENTED SCRIPTING LANGUAGE: that organizes software design around data, or objects, rather than
functions and logic. An object can be defined as a data field that has unique attributes and behavior.
Desktop development,
DataScience,
Network programming,
Machine Learning,
mathematics,
system scripting.
WHY CHOOSE PYTHON
ADVANTAGES OF PYTHON
LANGUAGE
DISADVANTAGES OF PYTHON
LANGUAGE
Python frameworks
Python frameworks automate the implementation of several tasks and give developers a structure for application
development. Each framework comes with its own collection of modules or packages that significantly reduce
development time
WEB FRAMEWORKS OF PYTHON
DATASCIENCE FRAMEWORKS OF
PYTHON
1) NumPy: Foundations for statistical
computing
2) Pandas: Simplified data processing
1.Tkinter
2. PyQt
3. Kivy
4. PySide
5. wxPython
6. PyGTK
GAME DEVELOPMENT FRAMEWORKS
OF PYTHON
1. Pygame
2. Pyglet
3. PyOpenGL
4. Panda3D
5. Kivy
6. Arcade
7. Pymunk
Popular website build with
Python
Installing Python on Windows
Step: 1
To download and install Python, go to Python's official website http://www.python.org/downloads/
Step 4
when installation completes you will see the message “setup was successful” on screen
IDLE Development Environment
Example
x = "Python is awesome"
print(x)
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
PRINT() FUNCTION CONT’ …
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
x=5
y = 10
print(x + y)
PRINT() FUNCTION CONT’ …
In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
The best way to output multiple variables in the print() function is to separate them with commas, which
even support different data types:
Example
x=5
y = "John"
print(x, y)
VARIABLES
Variables are containers for storing data values.
Python has no command for declaring a variable. A variable is created the moment you first
assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they have been
set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x
VARIABLES CONT’…
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
Example
x=5
y = "John“
print(type(x))
print(type(y))
VARIABLES CONT’…
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John" # is the same as
x = 'John'
VARIABLES CONT’…
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for
Python variables:
Variable names are case-sensitive (age, Age and AGE are three different
variables)
VARIABLES CONT’…
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
VARIABLES CONT’…
Many Values to Multiple Variables
Example
Note: Make sure the number of variables matches the number of values, or else
you will get an error.
VARIABLES CONT’…
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange“
print(x)
DATATYPES
Built-in Data Types
In programming, data type is an important concept. Variables can store data of different types, and different
types can do different things.
Python has the following data types built-in by default, in these categories:
You can get the data type of any object by using the type() function:
Example
In Python, the data type is set when you assign a value to a variable:
DATATYPES CONT’ …
Example Datatype
x = 20 int
x = 20.5 float
x = 1j complex
If you want to specify the data type, you can use the following constructor functions:
DATATYPES CONT’ …
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
COMMENTS
Comments can be used to explain Python code.
Creating a Comment
Example
#This is a comment
print("Hello, World!")
COMMENTS CONT’…
Multi-Line Comments
Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
COMMENTS CONT’…
Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!“)
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a
multiline comment
NUMBERS
Python Numbers
int
float
Complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
NUMBERS CONT’…
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
NUMBERS CONT’…
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
NUMBERS CONT’…
Complex
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
NUMBERS CONT’…
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Note: You cannot convert complex numbers into another number type.
NUMBERS CONT’…
Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
USER INPUT
Python allows for user input.
That means we are able to ask the user for input.
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Python Strings cont’…
Multiline Strings
Example
print(a)
Python Strings cont’…
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Python Strings cont’…
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Example
Example
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Python Slicing cont’ …
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
Example
Example
The strip() method removes any whitespace from the beginning or the end:
a = “ Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Python - Modify Strings cont’…
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Python – String concatenation
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
Example
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Python – Escape characters
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:
Example
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
txt = "We are the so-called "Vikings" from the north."
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
Python – Escape characters cont’…
Other escape characters used in Python:
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
Python – String Functions
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
Python – String Functions cont’…
Method Description
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string