Selasa, 12 Maret 2024

30 DAYS OF PYTHON BY ASABENEH (Pengembangan Aplikasi Web Based)

Built in functions

In Python we have lots of built-in functions. Built-in functions are globally available for your use that mean you can make use of the built-in functions without importing or configuring. Some of the most commonly used Python built-in functions are the following: print(), len(), type(), int(), float(), str(), input(), list(), dict(), min(), max(), sum(), sorted(), open(), file(), help(), and dir(). In the following table you will see an exhaustive list of Python built-in functions taken from python documentation.

Let us open the Python shell and start using some of the most common built-in functions.
Let us practice more by using different built-in functions
As you can see from the terminal above, Python has got reserved words. We do not use reserved words to declare variables or functions. We will cover variables in the next section.

I believe, by now you are familiar with built-in functions. Let us do one more practice of built-in functions and we will move on to the next section.

Variables

Variables store data in a computer memory. Mnemonic variables are recommended to use in many programming languages. A mnemonic variable is a variable name that can be easily remembered and associated. A variable refers to a memory address in which data is stored. Number at the beginning, special character, hyphen are not allowed when naming a variable. A variable can have a short name (like x, y, z), but a more descriptive name (firstname, lastname, age, country) is highly recommended.

Python Variable Name Rules A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables)

We will use standard Python variable naming style which has been adopted by many Python developers. Python developers use snake case(snake_case) variable naming convention. We use underscore character after each word for a variable containing more than one word(eg. first_name, last_name, engine_rotation_speed). The example below is an example of standard naming of variables, underscore is required when the variable name is more than one word.

When we assign a certain data type to a variable, it is called variable declaration. For instance in the example below my first name is assigned to a variable first_name. The equal sign is an assignment operator. Assigning means storing data in the variable. The equal sign in Python is not equality as in Mathematics.

Declaring Multiple Variable in a Line Multiple variables can also be declared in one line: Example: first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True print(first_name, last_name, country, age, is_married) print('First name:', first_name) print('Last name: ', last_name) print('Country: ', country) print('Age: ', age) print('Married: ', is_married) Getting user input using the input() built-in function. Let us assign the data we get from a user into first_name and age variables. Example: first_name = input('What is your name: ') age = input('How old are you? ') print(first_name) print(age) Data Types There are several data types in Python. To identify the data type we use the type built-in function. I would like to ask you to focus on understanding different data types very well. When it comes to programming, it is all about data types. I introduced data types at the very beginning and it comes again, because every topic is related to data types. We will cover data types in more detail in their respective sections. Checking Data types and Casting Check Data types: To check the data type of certain data/variable we use the type Example: # Different python data types # Let's declare variables with various data types first_name = 'Asabeneh' # str last_name = 'Yetayeh' # str country = 'Finland' # str city= 'Helsinki' # str age = 250 # int, it is not my real age, don't worry about it # Printing out types print(type('Asabeneh')) # str print(type(first_name)) # str print(type(10)) # int print(type(3.14)) # float print(type(1 + 1j)) # complex print(type(True)) # bool print(type([1, 2, 3, 4])) # list print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict print(type((1,2))) # tuple print(type(zip([1,2],[3,4]))) # set Casting: Converting one data type to another data type. We use int(), float(), str(), list, set When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with a string, the number should be first converted to a string. We will talk about concatenation in String section. Example: # int to float num_int = 10 print('num_int',num_int) # 10 num_float = float(num_int) print('num_float:', num_float) # 10.0 # float to int gravity = 9.81 print(int(gravity)) # 9 # int to str num_int = 10 print(num_int) # 10 num_str = str(num_int) print(num_str) # '10' # str to int or float num_str = '10.6' print('num_int', int(num_str)) # 10 print('num_float', float(num_str)) # 10.6 # str to list first_name = 'Asabeneh' print(first_name) # 'Asabeneh' first_name_to_list = list(first_name) print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h'] Numbers Number data types in Python: Integers: Integer(negative, zero and positive) numbers Example: ... -3, -2, -1, 0, 1, 2, 3 ... Floating Point Numbers(Decimal numbers) Example: ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... Complex Numbers Example: 1 + j, 2 + 4j, 1 - 1j Boolean A boolean data type represents one of the two values: True or False. The use of these data types will be clear once we start using the comparison operator. The first letter T for True and F for False should be capital unlike JavaScript. Example: Boolean Values print(True) print(False) Operators Python language supports several types of operators. In this section, we will focus on few of them. • Assignment Operators Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from w3school.

• Arithmetic Operators: 1. Addition(+): a + b 2. Subtraction(-): a – b 3. Multiplication(*): a * b 4. Division(/): a / b 5. Modulus(%): a % b 6. Floor division(//): a // b 7. Exponentiation(**): a ** b
Example:Integers # Arithmetic Operations in Python # Integers print('Addition: ', 1 + 2) # 3 print('Subtraction: ', 2 - 1) # 1 print('Multiplication: ', 2 * 3) # 6 print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number print('Division: ', 6 / 2) # 3.0 print('Division: ', 7 / 2) # 3.5 print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining print ('Division without the remainder: ',7 // 3) # 2 print('Modulus: ', 3 % 2) # 1, Gives the remainder print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2 Example:Floats # Floating numbers print('Floating Point Number, PI', 3.14) print('Floating Point Number, gravity', 9.81) Example:Complex numbers # Complex numbers print('Complex number: ', 1 + 1j) print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic. Example: # Declaring the variable at the top first a = 3 # a is a variable name and 3 is an integer data type b = 2 # b is a variable name and 3 is an integer data type # Arithmetic operations and assigning the result to a variable total = a + b diff = a - b product = a * b division = a / b remainder = a % b floor_division = a // b exponential = a ** b # I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions print(total) # if you do not label your print with some string, you never know where the result is coming from print('a + b = ', total) print('a - b = ', diff) print('a * b = ', product) print('a / b = ', division) print('a % b = ', remainder) print('a // b = ', floor_division) print('a ** b = ', exponentiation) Example: print('== Addition, Subtraction, Multiplication, Division, Modulus ==') # Declaring values and organizing them together num_one = 3 num_two = 4 # Arithmetic operations total = num_one + num_two diff = num_two - num_one product = num_one * num_two div = num_two / num_one remainder = num_two % num_one # Printing values with label print('total: ', total) print('difference: ', diff) print('product: ', product) print('division: ', div) print('remainder: ', remainder) Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force). Example: # Calculating area of a circle radius = 10 # radius of a circle area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power print('Area of a circle:', area_of_circle) # Calculating area of a rectangle length = 10 width = 20 area_of_rectangle = length * width print('Area of rectangle:', area_of_rectangle) # Calculating a weight of an object mass = 75 gravity = 9.81 weight = mass * gravity print(weight, 'N') # Adding unit to the weight # Calculate the density of a liquid mass = 75 # in Kg volume = 0.075 # in cubic meter density = mass / volume # 1000 Kg/m^3 Comparison Operators In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from w3shool.
Example: Comparison Operators print(3 > 2) # True, because 3 is greater than 2 print(3 >= 2) # True, because 3 is greater than 2 print(3 < 2) # False, because 3 is greater than 2 print(2 < 3) # True, because 2 is less than 3 print(2 <= 3) # True, because 2 is less than 3 print(3 == 2) # False, because 3 is not equal to 2 print(3 != 2) # True, because 3 is not equal to 2 print(len('mango') == len('avocado')) # False print(len('mango') != len('avocado')) # True print(len('mango') < len('avocado')) # True print(len('milk') != len('meat')) # False print(len('milk') == len('meat')) # True print(len('tomato') == len('potato')) # True print(len('python') > len('dragon')) # False # Comparing something gives either a True or False print('True == True: ', True == True) print('True == False: ', True == False) print('False == False:', False == False) In addition to the above comparison operator Python uses: • is: Returns true if both variables are the same object(x is y) • is not: Returns true if both variables are not the same object(x is not y) • in: Returns True if the queried list contains a certain item(x in y) • not in: Returns True if the queried list doesn't have a certain item(x in y) print('1 is 1', 1 is 1) # True - because the data values are the same print('1 is not 2', 1 is not 2) # True - because 1 is not 2 print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B print('coding' in 'coding for all') # True - because coding for all has the word coding print('a in an:', 'a' in 'an') # True print('4 is 2 ** 2:', 4 is 2 ** 2) # True Logical Operators Unlike other programming languages python uses keywords and, or and not for logical operators. Logical operators are used to combine conditional statements:
print(3 > 2 and 4 > 3) # True - because both statements are true print(3 > 2 and 4 < 3) # False - because the second statement is false print(3 < 2 and 4 < 3) # False - because both statements are false print('True and True: ', True and True) print(3 > 2 or 4 > 3) # True - because both statements are true print(3 > 2 or 4 < 3) # True - because one of the statements is true print(3 < 2 or 4 < 3) # False - because both statements are false print('True or False:', True or False) print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False print(not True) # False - Negation, the not operator turns true to false print(not False) # True print(not not True) # True print(not not False) # False Strings Text is a string data type. Any data type written as text is a string. Any data under single, double or triple quote are strings. There are different string methods and built-in functions to deal with string data types. To check the length of a string use the len() method. • Creating a String letter = 'P' # A string could be a single character or a bunch of texts print(letter) # P print(len(letter)) # 1 greeting = 'Hello, World!' # String could be made using a single or double quote,"Hello, World!" print(greeting) # Hello, World! print(len(greeting)) # 13 sentence = "I hope you are enjoying 30 days of Python Challenge" print(sentence) Multiline string is created by using triple single (''') or triple double quotes ("""). See the example below. multiline_string = '''I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.''' print(multiline_string) # Another way of doing the same thing multiline_string = """I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.""" print(multiline_string) • String Concatenation We can connect strings together. Merging or connecting strings is called concatenation. See the example below: first_name = 'Asabeneh' last_name = 'Yetayeh' space = ' ' full_name = first_name + space + last_name print(full_name) # Asabeneh Yetayeh # Checking the length of a string using len() built-in function print(len(first_name)) # 8 print(len(last_name)) # 7 print(len(first_name) > len(last_name)) # True print(len(full_name)) # 16 • Escape Sequences in Strings In Python and other programming languages \ followed by a character is an escape sequence. Let us see the most common escape characters: \n: new line \t: Tab means(8 spaces) \\: Back slash \': Single quote (') \": Double quote (") Now, let us see the use of the above escape sequences with examples. print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break print('Days\tTopics\tExercises') # adding tab space or 4 spaces print('Day 1\t5\t5') print('Day 2\t6\t20') print('Day 3\t5\t23') print('Day 4\t1\t35') print('This is a backslash symbol (\\)') # To write a backslash print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote # output I hope every one is enjoying the Python Challenge. Are you ? Days Topics Exercises Day 1 5 5 Day 2 6 20 Day 3 5 23 Day 4 1 35 This is a backslash symbol (\) In every programming language it starts with "Hello, World!" • String formatting Old Style String Formatting (% Operator) In Python there are many ways of formatting strings. In this section, we will cover some of them. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s", "%d", "%f", "%.number of digitsf". %s - String (or any object with a string representation, like numbers) %d - Integers %f - Floating point numbers "%.number of digitsf" - Floating point numbers with fixed precision # Strings only first_name = 'Asabeneh' last_name = 'Yetayeh' language = 'Python' formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language) print(formated_string) # Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas'] formated_string = 'The following are python libraries:%s' % (python_libraries) print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']" • New Style String Formatting (str.format) This formatting is introduced in Python version 3. first_name = 'Asabeneh' last_name = 'Yetayeh' language = 'Python' formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language) print(formated_string) a = 4 b = 3 print('{} + {} = {}'.format(a, b, a + b)) print('{} - {} = {}'.format(a, b, a - b)) print('{} * {} = {}'.format(a, b, a * b)) print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal print('{} % {} = {}'.format(a, b, a % b)) print('{} // {} = {}'.format(a, b, a // b)) print('{} ** {} = {}'.format(a, b, a ** b)) # output 4 + 3 = 7 4 - 3 = 1 4 * 3 = 12 4 / 3 = 1.33 4 % 3 = 1 4 // 3 = 1 4 ** 3 = 64 # Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal print(formated_string) String Interpolation / f-Strings (Python 3.6+) Another new string formatting is string interpolation, f-strings. Strings start with f and we can inject the data in their corresponding positions. a = 4 b = 3 print(f'{a} + {b} = {a +b}') print(f'{a} - {b} = {a - b}') print(f'{a} * {b} = {a * b}') print(f'{a} / {b} = {a / b:.2f}') print(f'{a} % {b} = {a % b}') print(f'{a} // {b} = {a // b}') print(f'{a} ** {b} = {a ** b}') • Python Strings as Sequences of Characters Python strings are sequences of characters, and share their basic methods of access with other Python ordered sequences of objects – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables. Accessing Characters in Strings by Index In programming counting starts from zero. Therefore the first letter of a string is at zero index and the last letter of a string is the length of a string minus one. language = 'Python' first_letter = language[0] print(first_letter) # P second_letter = language[1] print(second_letter) # y last_index = len(language) - 1 last_letter = language[last_index] print(last_letter) # n If we want to start from right end we can use negative indexing. -1 is the last index. language = 'Python' last_letter = language[-1] print(last_letter) # n second_last = language[-2] print(second_last) # o • Slicing Python Strings In python we can slice strings into substrings. language = 'Python' first_three = language[0:3] # starts at zero index and up to 3 but not include 3 print(first_three) #Pyt last_three = language[3:6] print(last_three) # hon # Another way last_three = language[-3:] print(last_three) # hon last_three = language[3:] print(last_three) # hon • Reversing a String We can easily reverse strings in python. greeting = 'Hello, World!' print(greeting[::-1]) # !dlroW ,olleH Skipping Characters While Slicing It is possible to skip characters while slicing by passing step argument to slice method. language = 'Python' pto = language[0:6:2] # print(pto) # Pto • String Methods There are many string methods which allow us to format strings. See some of the string methods in the following example: 1. capitalize(): Converts the first character of the string to capital letter 2. count(): returns occurrences of substring in string, count(substring, start=.., end=..). The start is a starting indexing for counting and end is the last index to count. 3. endswith(): Checks if a string ends with a specified ending 4. expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument 5. find(): Returns the index of the first occurrence of a substring, if not found returns -1 6. rfind(): Returns the index of the last occurrence of a substring, if not found returns -1 7. format(): formats string into a nicer output 8. index(): Returns the lowest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1). If the substring is not found it raises a valueError. 9. rindex(): Returns the highest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1) 10. isalnum(): Checks alphanumeric character 11. isalpha(): Checks if all string elements are alphabet characters (a-z and A-Z) 12. isdecimal(): Checks if all characters in a string are decimal (0-9) 13. isdigit(): Checks if all characters in a string are numbers (0-9 and some other unicode characters for numbers) 14. isnumeric(): Checks if all characters in a string are numbers or number related (just like isdigit(), just accepts more symbols, like ½) 15. isidentifier(): Checks for a valid identifier - it checks if a string is a valid variable name 16. islower(): Checks if all alphabet characters in the string are lowercase 17. isupper(): Checks if all alphabet characters in the string are uppercase 18. join(): Returns a concatenated string 19. strip(): Removes all given characters starting from the beginning and end of the string 20. replace(): Replaces substring with a given string 21. split(): Splits the string, using given string or space as a separator 22. title(): Returns a title cased string 23. swapcase(): Converts all uppercase characters to lowercase and all lowercase characters to uppercase characters 24. swapcase(): Converts all uppercase characters to lowercase and all lowercase characters to uppercase characters

Tidak ada komentar:

Posting Komentar

Python Mysql w3school

Python dapat digunakan dalam aplikasi database. Salah satu database yang paling populer adalah MySQL. 1.Instal Pengandar MySQL 2.Uji K...