Python: Zero to Hero

Today

First Line Of Code

print('Hello My Lovely!')

Data Type

print(1+2) -- 3
print(1+2.5) -- 3.5
print(1+'2') -- Type Eror can't add str with int

Variabel

Name that we give to certain values on our code

a = 2+3
-- a here is variabel

Function

Function is usefull for reusable code

def luasSegitga(alas, tinggi):
	return luas = alas*tinggi/2

Comparison Operators

Python comparison operators return Boolean results: True or False.

Symbol Name Expression Description
== Equality operator a == b a is equal to b
!= Not equal to operator a != b a is not equal to b
> Greater than operator a > b a is larger than b
>= Greater than or equal to operator a >= b a is larger than or equal to b
< Less than operator a < b a is smaller than b
<= Less than or equal to operator a <= b a is smaller than or equal to b

Comparison Operators With Strings

Python use to compare very left unicode number from this table when doing with string:

Untitled

Expression Description
"a" == "a" If string "a" is identical to string "a", returns True. Else, returns False
"a" != "b" If string "a" is not identical to string "b"
"a" > "b" If string "a" has a larger Unicode value than string "b"
"a" >= "b" If the Unicode value for string "a" is greater than or equal to the Unicode value of string "b"
"a" < "b" If string "a"  has a smaller Unicode value than string "b"
"a" <= "b" If the Unicode value for string "a" is smaller than or equal to the Unicode value of string "b"

Logical Operators

When Python logical operators are used with comparison operators, the interpreter will return Boolean results (True or False):

a == a and a != b True if both sides are True, otherwise False.
a > b or a <= c True if either side is True. False if both sides are False.
not a == b True if the statement is False, False if the statement is True.

Membership Operators

Untitled

If - Elif - Else Statement

Untitled

For Loops and Nested Loops

Untitled

While Loops

Untitled

Recursion

this usefull when we work on like Tree sturcture. can count all the goup on sub branch or subsub branch in one file. (A recursive function will usually have this structure)

A recursive function must include a recursive case and base case. The recursive case calls the function again, with a different value. The base case returns a value without calling the same function.

A recursive function will usually have this structure:

def recursive_function(parameters):
    if base_case_condition(parameters):
        return base_case_value
    recursive_function(modified_parameters)

Make List then Print into one single string

    n = int(input()) # make input feature
    num = list(range(1,n+1)) # make list dengan isi 1,2,3
 
    # for loop to convert int to str
    for i in range (n):
        num[i]=str(num[i])
 
    print(''.join(num))

String operations

String methods

will print ‘this is try’

print("hello {}, your lucky number is {}".format(name, number))
price = 7.5
price_with_tax = price*1.09
 
print("base price: ${:2f}. With tax: ${:2f}".format(price, price_with_tax))

will print “base price: $7.50. With tax: $8.18”

Another Example:

Untitled

“>” for Alight to right, “>6” for Alight to right on 6 spaces

Expr Meaning Example
{:d} integer value '{:d}'.format(10.5) → '10'
{:.2f} floating point with that many decimals '{:.2f}'.format(0.5) → '0.50'
{:.2s} string with that many characters '{:.2s}'.format('Python') → 'Py'
{:<6s} string aligned to the left that many spaces '{:<6s}'.format('Py') → 'Py    '
{:>6s} string aligned to the right that many spaces '{:>6s}'.format('Py') → '    Py'
{:^6s} string centered in that many spaces '{:^6s}'.format('Py') → '  Py '

List

x = []

def get_word(sentence, n):
	# Only proceed if n is positive
	if n > 0:
		words = sentence.split()
		# Only proceed if n is not more than the number of words
		if n <= len(words):
			return(words[n-1])
	return("")
 
print(get_word("This is a lesson about lists", 4)) # Should print: lesson
print(get_word("This is a lesson about lists", -4)) # Nothing
print(get_word("Now we are cooking!", 1)) # Should print: Now
print(get_word("Now we are cooking!", 5)) # Nothing

Adding Data into List

df = [1,2,3,4]

df.append(5)
##will make df = [1,2,3,4,5]
df.insert(0,'nomo')
#will make df = ['nomo',0,1,2,3,4,5]

Remove data from List

df = ['nomo',0,1,2,3,4,5]

df.remove('nomo')
#will make df = [0,1,2,3,4,5]
df = ['nomo',0,1,2,3,4,5]
df.pop(2)
#will make df = ['nomo',0,2,3,4,5]

Changing data from list

df = ['nomo',0,1,2,3,4,5]
df[0] = 9
#will make df = [9,0,1,2,3,4,5]

List Comprehension

number = []
for x in range (1,10):
	number.append(x)
number
## Output : 1,2,3,4,5,6,7,8,9

Actually that task can write on shorter code like

number = [x for x in range (1,10)]

other example

def odd_numbers(n):
	return [x for x in range (1,n+1) if x % 2 != 0]
 
print(odd_numbers(5))  # Should print [1, 3, 5]

Tuple

like list but immutable

def file_size(file_info):
	fileName, fileType, bytes= file_info
	return("{:.2f}".format(bytes / 1024))
 
print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21

Iterating over Lists and Tuples

animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animal:
	chars += len(animal)
print("Total characters: {}, Average length {}".format(chars, chars/len(animals)))
 
#Output : Total characters: 22, Average length 5.5

Enumerate Function

winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
	print("{} - {}".format(index + 1, person))
 
#Output : 1 - Ashley
			#   2 - Dylan
			#   3 - Reese

Use Case