Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Python

The document discusses Python keywords and functions related to strings, lists, loops, and other basic data types and operations. It provides code examples and explanations of print(), string methods like upper() and lower(), list methods like append() and insert(), and functions like range() and len().

Uploaded by

james3611220
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python

The document discusses Python keywords and functions related to strings, lists, loops, and other basic data types and operations. It provides code examples and explanations of print(), string methods like upper() and lower(), list methods like append() and insert(), and functions like range() and len().

Uploaded by

james3611220
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

The Python keywords

Print()

Code print(‘Hello Python world!’)

Result Hello Python world!

Code a = “Hello Python world!”

Print(a)

Result Hello Python world!

a.title()

code a = ‘ada lovelace’

print(a.title())

result Ada Lovelace

a.upper()

code a = ‘Ada Lovelace’

print(a.upper())

result ADA LOVELACE

a.lower()

code a = ‘Ada Lovelace’

print(a.lower())

result ada lovelace


f”{a} {b}”

code a = ‘ada’

b = “lovelace”

c = f’{a} {b}’

print(c)

result ada lovelace

code a = ‘ada’

b = “lovelace”

c = f’{a} {b}’

d = f”Hello, {c.title()}!”

print(d)

result Hello, Ada Lovelace!

“\t”

Code print(‘\tPython’)

Result Python

“\n”

Code print(“\nPython”)

Result

Python

a.rstrip()

code a = ‘Python ‘

print(a.rstrip())

result Python

a.lstrip()

code a = ‘ Python’
print(a.lstrip())

result Python

a.strip()

code a = ‘ Python ‘

b = “ Java”

print(a.strip())

print(b.strip())

result Python

Java

a.removeprefix(“b”)

code a = ‘box’

print(a.removeprefix(“b”))

result ox

a.removesuffix(“b”)

code a = ‘tub’

print(a.removesuffix(“b”)

result tu

a.append(‘C’)

code a = [‘A’, ‘B’]

print(a.append(‘C’))

result [A, B, C]

a.insert(2, ‘C’)

code a = [‘A’, ‘B’, ‘D’]

print(a.insert(2, ‘C’))
result [A, B, C, D]

del a[1]

code a = [‘A’, ‘B’, ‘C’]

del a[1]

print(a)

result [A, C]

a.sort()

code a = [‘a’, ‘c’, ‘b’, ‘2’, ‘1’, ‘!’]

a.sort()

print(a)

result [‘!’, ‘1’, ‘2’, ‘a’, ‘b’, ‘c’]

code a = [‘a’, ‘c’, ‘b’, ‘2’, ‘1’, ‘!’]

a.sort(reverse = True)

print(a)

result [‘c’, ‘b’, ‘a’, ‘2’, ‘1’, ‘!’]

sorted(a)

code a = [‘a’, ‘c’, ‘b’, ‘2’, ‘1’, ‘!’]

print(sorted(a))

result [‘!’, ‘1’, ‘2’, ‘a’, ‘b’, ‘c’]

a.reverse()

code a = [‘a’, ‘b’, ‘c’]

a.reverse()

print(a)

result [‘c’, ‘b’, ‘a’]


len(a)

code a = [‘a’, ‘b’, ‘c’]

print(len(a))

result 3

Looping

Code a = [‘A’, ‘B’, ‘C’]

For b in a:

Print(b)

Result A

Code for n in range(0, 6, 2):

Print(n)

Result 0

Min(a)

Code a = [1, 0, 3, -1, 2]

Print(min(a))

Result -1

Max(a)

Code a = [1, 0, 2, 3, -1]

Print(max(a))

Result 3

Sum(a)
Code a = [1, 2, 3, 4]

Print(sum(a))

Result 10

List Comprehension

Code a = [ b(c) for c in d]

Result e

Reference b is a function. D is a list or a numerical sequence. E is a list.

Slicing a list

Code A = [‘a’, ‘b’, ‘c’, ‘d’]

Print(A[1 : 3])

Result [‘b’, ‘c’]

Chapter 1

Variables and simple data types

Variable

A variable contains alphabet(s), number(s) and underscore(s), and it carries data(s).

Variable Modification

A variable can be modified without creating a new variable, by setting again. For example,

Code a = “a”

Print(a)

A = a.upper()
Print(a)

Result a

Code a = “a”

If a == “a”:

A=0

Print(a)

Result 0

Note

A variable should be created clearly for the Python interpreter to make it easy to read the variable
without mixing with the Python keyword or the integer.

A variable shouldn’t be start with a number.

A variable shouldn’t be thought as a box but as a label that is assigned to certain data(s).

Only the last updated data(s) of the variable is counted.

String

A string carries data(s) that is only affected by the string related Python keyword(s) and is put in single or
double quote(s).

Number

Numbers are divided into integers which aren’t decimals and floats which are decimals. Both of them
can add by using +, substrate by using -, multiply by using *, divide by using /, power by ** and find
remainder by using %.

Note

Every calculations with float(s) will be resulted as float(s).


A few decimal errors can be occurred in every programming language, and in python, the error can be
calculation such as 0.1 + 0.2 in which the answer is 0.30000000000000004, or 3 * 0.1 in which the
answer is also 0.30000000000000004.

Underscores can be used in number to make it readable such as 1_000_000_000_000 for


1000000000000, and they will be ignored by the Python interpreter.

Multiple Assignment

Variables can be assigned by using only one sentence in which each is separated by comma(s). For
example,

Code x, y, z = 0, 1, 2

Constant

A constant is written using capital letter(s) and used to describe that this variable will not change.

Chapter 2

List

List

A list contains more than one data in a particular order and these informations are separated by comma
and are put in square brackets.

Accessing an item in a list

In a list, the items are ordered, so that each item can be accessed by putting its position number in
square brackets after the variable of the list without spacing. For example,

Code bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

Print(bicycles[0])
Print(bicycles[-1].title())

Message = f”My first bicycle was a {bicycles[-3].title()}.”

Result trek

Specialized

My first bicycle was a Cannondale.

Modifying an item in a list

In a list, each item can be modified by accessing it. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

Print(motorcycles)

Motorcycles[0] = ‘ducati’

Print(motorcycles)

Result [‘honda’, ‘yamaha’, ‘suzuki’]

[‘ducati’, ‘yamaha’, ‘suzuki’]

Inserting a new item into a list

In a list, any new item can be inserted into any position of the list, by using insert(), a Python keyword,
putting the position number and then, placing a comma to set the new item after it, and the rest of the
list will be followed by the new item with their recently changed positions. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

Motorcycles.insert(0, ‘ducati’)

Print(motorcycles)

Result [‘ducati’, ‘honda’, ‘yamaha’, ‘suzuki’]

Note

The Python keyword, insert(), set the item to a certain position and that position can’t be changed that
when another item is also placed to the same position, that another item was moved to the right of it.
Appending a new item to the end of a list

In a list, by using append(), a Python keyword, any new item can be added(appended) to the end of the
list. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

Print(motorcycles)

Motorcycles.append(‘ducati’)

Print(motorcycles)

Result [‘honda’, ‘yamaha’, ‘suzuki’]

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

Removing an item using the del statement

In a list, an item can be removed by putting its position in the square brackets after the list’s variable
which follows del, the Python keywords. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

Print(motorcycles)

Del motorcycles[0]

Print(motorcycles)

Result [‘honda’, ‘yamaha’, ‘suzuki’]

[‘honda’, ‘suzuki’]

Removing an item using the Pop method

In a list, to remove an item according to its position, the position is put into the square brackets and to
recall the recently removed item, a variable must be set. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]

First_owned = motorcycles.pop(0)

Print(f”The first motorcycle I owned was a {first_owned.title()}.”)

Result The first motorcycle I owned was a Honda.


Removing the information(s) from a list

In a list, the exact value(s) or the variable carrying it, is put into the round brackets of remove(), a Python
keyword, to remove the value(s),the information(s) carried by the item, and to recall the recently
removed information(s), a variable must be set. For example,

Code motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

Print(motorcycles)

Too_expensive = ‘ducati’

Motorcycles.remove(too_expensive)

Print(motorcycles)

Print(f”\nA {too_expensive.title()} is too expensive for me.”)

Result [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

[‘honda’, ‘yamaha’, ‘suzuki’]

A Ducati is too expensive for me.

Note

The remove(), a Python keyword, is also used to remove the data(s) that is repeated throughout a list.

Order of a list

Sorting a list temporarily

In a list, the original order can be restored in a definite order temporarily by placing the variable of the
list in the brackets of sorted(), a Python keyword.

Sorting a list permanently

In a list, the original order can be restored in a definite order permanently by using sort(), a Python
keyword, and to restore in the opposite order, an argument, reverse = True, is put in the round brackets.

Reversing a list

In a list, the order can be reversed by putting reverse(), a Python keyword, after the variable of the list.
Length of a list

In a list, to calculate the number of item(s), len(), a Python keyword, can be used by putting the variable
into the round brackets.

Looping through a list

In a list, to refer each item, the variable which represents each of the items is put after a Python
keyword, for, and then, a Python keyword, in, follows the statement putting the variable of the list
behind it with a comma after the variable. Then, to perform the same task for each referred item, every
code for the task must be written after a tab at least. For example,

Code magicians = [‘alice’, ‘david’, ‘carolina’]

For magician in magicians:

Print(magician)

Result alice

David

Carolina

Looping a numerical sequence

To loop a numerical sequence, a Python function, range(), is used by putting starting number(not
necessary) which is 0 at default and known as start, by putting stopping number(necessary) which is
known as stop, and by putting stepping number which defines how many steps are taken for the count ,
is 1 at default and known as step. For example,

Code for value in range(0, 6, 2):

Print(value)

Result 0

4
Note

While looping a numerical sequence, the stopping number will be excluded.

By using range(), a Python function, an odd numerical sequence, an even numerical list or some
numerical lists can be created as the creator’s imagination.

Contracting a numerical sequence directly

A numerical sequence can be built by creating the variable which represents the list and directly
modifying the variable which represents the item. For example,

Code value = [a**2 for a in range(0,6,2)]

Print(value)

Result [0, 4, 16]

Creating a numerical list using

Range(),a Python keyword

To create a numerical list, the numerical sequence formed by range(),a Python keyword, is created in the
round brackets of a python keyword, list(). For example,

Code numbers = list(range(1, 6))

Print(numbers)

Result [1, 2, 3, 4, 5]

Slicing a list

To work with a specific segment of the list, an arrangement in which the variable of the list is followed by
the first number, the symbol of ratio, and the second number inside the squared brackets. The first
number is the starting item and the second number is the ending item. In addition, if there is only a first
number which has a negative sign, the list will be counted backward and that first number will be the
number of items in the resultant list. For example,

Code A = [“a”, “b”, “c”, “d”]

Print(A[1 : 3])

Result [‘b’, ‘c’]

Code A = [“a”, “b”, “c”, “d”]

Print(A[-1 : ])
Result [d]

Code A = [“a”, “b”, “c”, “d”]

Print(A[ : -2])

Result [‘a’, ‘b’]

Code A = [“a”, “b”, “c”, “d”]

Print(A[ : ])

Result [‘a’, ‘b’, ‘c’, 'd']

Note

The default of the number of excluded item is zero.

The default of the number of included item is the same as the number of all items in the list.

The negative number cannot be used if both of the first number and the second number exist at the
same time.

Combination with “ if “ statement

Code A = [‘a’, ‘b’, ‘c’, ‘d’]

For i in A[ : 3]:

Print(i)

Result a

You might also like