You are on page 1of 33

PYTHON

Python is a popular programming language. It was created


by Guido van Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

1
PYTHON INSTALL
Search CMD or Command Prompt

Download Link:
https://www.python.org/
2
PYTHON QUICKSTART
Python is an interpreted programming language, this means that as a
developer you write Python (.py) files in a text editor and then put those files
into the python interpreter to be executed.

3
THE PYTHON COMMAND LINE
Type the following on the Windows, Mac or Linux command line:

Or, if the "python" command did not work, you can try "py":

4
Which will write "Hello, World!" in the command line:

following to quit the python command line interface:

5
EXECUTE PYTHON SYNTAX

Print()

PYTHON INDENTATION
if 5 > 2:
  print("Five is greater than two!")
if 5 > 2: if 5 > 2:
  print("Five is greater than two!")    print("Five is greater than two!")

ERROR
ERROR if 5 > 2:
if 5 > 2:   print("Five is greater than two!")
print("Five is greater than two!")    print("Five is greater than two!")

6
PYTHON VARIABLES

GET THE TYPE

CASTING

7
VARIABLE NAMES

8
9
10
11
OUTPUT MULTIPLE VARIABLES (OPERATOR)
OUTPUT VARIABLES

OUTPUT MULTIPLE VARIABLES (COMA)

12
GLOBAL VARIABLES

13
THE GLOBAL KEYWORD

14
PYTHON COMMENTS

MULTILINE STRING
(TRIPLE QUOTES)

MULTI LINE COMMENTS

15
DATA TYPES

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

16
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello“ bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
17
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry“)) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
18
Float can also be scientific numbers
PYTHON NUMBERS with an "e" to indicate the power of
There are three numeric types in Python:
10.
Int x = 1    # int x = 35e3
float y = 2.8  # float y = 12E4
Complex z = 1j   # complex z = -87.7e100
Int
Output
Int, or integer, is a whole number, positive or negative, without 35000.0
decimals, of unlimited length. 120000.0
x = 1 -8.77e+101
y = 35656222554887711
z = -3255522 Complex numbers are written with a
"j" as the imaginary part:
Float
x = 3+5j
Float, or "floating point number" is a number, positive or negative, y = 5j
containing one or more decimals. z = -5j

x = 1.10 Output:
y = 1.0 (3+5j)
z = -35.59 5j
(-0-5j)
PYTHON NUMBERS

Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:

x = 1    # int
y = 2.8  # float
z = 1j   # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

20
PYTHON CASTING
There may be times when you want to specify a type on to a variable.
int()
x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float()
x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2
str()
x = str("s1")  # x will be 's1'
y = str(2)     # y will be '2'
z = str(3.0)   # z will be '3.0'

21
PYTHON STRINGS
Strings in python are surrounded by either single quotation marks, or
double quotation marks. 'hello' is the same as "hello".
print("Hello")
print('Hello’)
Assign String to a Variable
a = "Hello"
print(a)
You can assign a multiline string to a variable by using three quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

22
PYTHON - SLICING STRINGS
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!" llo
print(b[2:5])
Slice From the Start
Get the characters from the start to position 5 (not included):
b = "Hello, World!" Hello
print(b[:5])
Slice To the End
Get the characters from position 2, and all the way to the end:
llo, World!
b = "Hello, World!"
print(b[2:])
Negative Indexing
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
orl
b = "Hello, World!"
print(b[-5:-2])
23
PYTHON - MODIFY STRINGS

The upper() method returns the string in


upper case:
a = "Hello, World!" The replace() method replaces a string with
print(a.upper()) another string:
a = "Hello, World!"
print(a.replace("H", "J"))
The lower() method returns the string in
lower case:
a = "Hello, World!" The split() method splits the string into
print(a.lower()) substrings if it finds instances of the
separator:
a = "Hello, World!"
The strip() method removes any print(a.split(",")) # returns ['Hello', '
whitespace from the beginning or the end: World!']
a = " Hello, World! "
print(a.strip()) # returns "Hello,
World!"

24
PYTHON - STRING CONCATENATION

To concatenate, or combine, two strings you can use the + operator.


a = "Hello"
b = "World"
c = a + b
print(c)

To add a space between them, add a " ":


a = "Hello"
b = "World"
c = a + " " + b
print(c)

25
PYTHON - FORMAT - STRINGS

As we learned in the Python Variables chapter, we cannot


combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using


the format() method!
age = 36
txt = "My name is John, and I am {}“
print(txt.format(age))

26
PYTHON - FORMAT - STRINGS
The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
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))

27
PYTHON - ESCAPE CHARACTERS
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.“

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."

28
OTHER ESCAPE CHARACTERS USED IN PYTHON:
\’ Single Quote

#This example erases one character (backspace):


\\ Backslash txt = "Hello \bWorld!"
print(txt)
\n New Line
#A backslash followed by three integers will result in a octal
\r Carriage Return value:
txt = "\110\145\154\154\157"
print(txt)
\t Tab

#A backslash followed by an 'x' and a hex number


\b Backspace represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
\ooo Octal value

\xhh Hex value

29
PYTHON - STRING METHODS
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
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet

30
PYTHON - STRING METHODS
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
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
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

31
PYTHON - STRING METHODS
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string

32
PYTHON - STRING METHODS
split() Splits the string at the specified separator, and returns a list
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

33

You might also like