Congratulations on your decision to participate in the 30 day Python Programming challenge. In this challenge, you will learn everything you need to be a python programmer and the entire programming concept. At the end of the challenge, you will receive a 30DaysOfPython programming challenge certificate.
1. Day 1 - Introduction
Python is a high-level programming language for general-purpose programming. It is an open source, interpretive and object-oriented programming language. Python was created by Guido van Rossum, a Dutch programmer. The name of Python programming language comes from the British sketch comedy series Month Python's flying circle. The first version was released on February 20, 1991. This 30 day Python challenge will help you gradually learn the latest version of python, Python 3.
This challenge is designed for beginners who want to learn the Python programming language. It may take 30 to 100 days to complete the challenge. It mainly depends on personal ability. Those with good logical thinking may learn it in 30 days.
1.1 why Python?
It is a programming language very close to human language, so it is easy to learn and use. Python is used by various industries and companies (including Google). It has been used to develop Web applications, desktop applications, system management and machine learning libraries.
1.2 environment setting
Install Python
To run Python scripts, you need to install python. Let's download python. If you are a Windows user. Click the button circled in red.
If you are a macOS user. Click the button circled in red.
To check whether python is installed, write the following command on the device terminal.
Python – version
As can be seen from the terminal, I am currently using Python version 3.7.5. Your Python version may be different from mine. It should be 3.6 or later. It would be great if you could see the python version. Python is installed on your machine. Continue to the next section.
Python Shell
Python is an interpretative scripting language, so it does not need to be compiled. This means that it executes code line by line. Python comes with a Python Shell (Python Interactive Shell). It is used to execute a single Python command and get the results.
The Python Shell waits for Python code from the user. When you enter the code, it interprets the code and displays the results on the next line. Open the terminal or command prompt (cmd) and write:
Python
The python interactive shell is open and is waiting for you to write Python scripts. You will write a python script next to this symbol > > > and click Enter. Let's write our first script on the python script shell.
After the above step is completed, you can write the first Python script on the python interactive shell. How do we close the python interactive shell? To close the shell, write the exit() command next to this symbol and press Enter.
Now you know how to open the Python interactive shell and how to exit it.
If you write a script that Python understands, python will give you the result, otherwise it will return an error. Let's deliberately make a mistake. Python will return an invalid syntax error.
From the returned error, we can see that Python is very smart. It knows that the error we made is Syntax Error: invalid syntax. Using X as multiplication in Python is a syntax error because x is not a valid syntax in Python. We multiply with an asterisk * instead of X. The error returned clearly shows what to fix.
The process of identifying and eliminating errors from programs is called debugging. Let's debug it with * instead of x.
Fix syntax errors
Our errors were fixed, the code ran, and we got the results we expected. As a programmer, you will see such errors every day. You must be good at debugging and understand the types of errors you face. Sometimes, the errors you may encounter are syntax error, IndexError, NameError, ModuleNotFoundError, KeyError exception, import error, AttributeError error, type error, ValueError exception, ZeroDivisionError, etc.
Let's practice how to use the python interactive shell. Go to your terminal or command prompt and enter the word python.
Python interactive shell is open. Let's do some basic mathematical operations: addition, subtraction, multiplication, division, module and index.
Before writing any Python code, let's do some mathematical operations:
2 + 3 = 5
3 - 2 = 1
3 * 2 = 6
3 / 2 = 1.5
3 ^ 2 = 3 x 3 = 9
In python, we have the following additional operations:
3% 2 = 1 = > means remainder
3 / / 2 = 1 = > this means that the remainder is removed
We change the above mathematical expression into Python code and write a comment at the beginning of the shell.
We can leave some text in our code to make our code more readable. Comments in python begin with hash# symbols.
#Comments start with hash #This is a Python Comment because it takes (#)Symbol beginning
Mathematics on python shell
Write exit() on the shell, close the open shell, open it again, and practice writing text on the Python shell.
Writing strings on a python shell
1.3Python Foundation
Python syntax
Python scripts can be written in a Python shell or code editor. Python files have a. py extension.
Python indent
Indents are spaces in text. Many languages use indentation to improve code readability, but python uses indentation to create code blocks. In other programming languages, braces are used to create blocks of code rather than indents. One of the common errors in writing python code is indentation errors.
notes
Comments are important to make the code more readable and to leave comments in our code. Python does not run the comment part of our code. Any text in python that begins with hash(#) is a comment.
Example: single line notes
#This is the first comment #This is the second comment # Python is swallowing the world
Example: multiline comment
If not assigned to a variable, triple quotes can be used for multiline comments
" " "This is a multiline comment Multiline comments require multiple lines . python Eating the world " " "
data type
There are several types of data types in Python. Let's start with the most common. Other sections will detail the different data types. For now, let's go through the different data types and get familiar with them.
number
- Integer: integer (negative, zero and positive) number examples:... - 3, - 2, - 1, 0, 1, 2, 3
- Floating point number: decimal number example... - 3.5, - 2.25, - 1.0, 0.0, 1.1, 2.2, 3.5
- Complex examples 1 + j, 2 + 4j
String
A collection of one or more characters under single or double quotation marks. If a string has more than one sentence, we use triple quotes.
example:
'Asabeneh' 'Finland' 'Python' 'I like teaching' 'I hope you enjoy 30 DaysOfPython The first day of the challenge'
Boolean value
The Boolean data type is a True or False value. T and F should always be capitalized.
example:
True # Is the light on? If If the light is on, the value is True False # Is the light on? If off, the value is False
list
A Python list is an ordered collection that allows you to store items of different data types. Lists are similar to arrays in JavaScript.
example:
[ 0 , 1 , 2 , 3 , 4 , 5 ] # Are the same data type - numeric list [ 'Banana' , 'Orange' , 'Mango' , 'Avocado' ] # All same data types - a string list (fruit) [ 'Finland' , 'Estonia' , 'Sweden' , 'Norway' ] # All same data types - string list (country) [ 'Banana' , 10 , False , 9.81 ]# Different data types in the list - strings, integers, Booleans, and floating point numbers
Dictionaries
Python dictionary objects are unordered collections of data in the form of key value pairs.
example:
{ 'first_name' : 'Asabeneh' , 'last_name' : 'Yetayeh' , 'country' : 'Finland' , 'age' : 250 , 'is_married' : True , 'skills' :[ 'JS' , 'React' , 'node','Python' ] }
tuple
Tuples are ordered collections of different data types (such as lists), but tuples cannot be modified once they are created. They are immutable.
example:
( 'Asabeneh' , 'Pawel' , 'Brook' , 'Abraham' , 'Lidiya' ) # name
("Earth "," Jupiter "," Neptune "," Mars "," Venus "," Saturn "," Uranus "," Mercury ")#planet discharge
aggregate
A collection is a collection of data types similar to lists and tuples. Unlike lists and tuples, collections are not ordered collections of items. As in mathematics, set in Python stores only unique items.
In a later section, we will describe each Python data type in detail.
example:
{ 2 , 4 , 3 , 5 } { 3.14 , 9.81 , 2.7 } # Order is not important in the set
Check data type
To check the data type of some data / variables, we use the type function. In the following terminals, you will see different Python data types:
Python file
First open your project folder, 30DaysOfPython. If you do not have this folder, create a folder called 30DaysOfPython. In this folder, create a file called helloworld.py.
The Python shell prints without using print. To see our results, we should use the built-in function * print(). The print() built-in function has one or more parameters printed as follows ("argument1", "parameter 2", "parameter 3"). See the example below.
example:
The file name is helloworld.py
# Day 1 - 30DaysOfPython challenge print ( 2 + 3 ) #Addition (+) print ( 3 - 1 ) #Subtraction (-) print ( 2 * 3 ) #Multiplication (*) print ( 3 / 2 ) # Division (/) print ( 3 ** 2 ) ) # Index (* *) Print( 3 % 2 ) # Modulus (%) Print( 3 // 2) # floor division operator (/ /) # Check data type print ( type ( 10 )) # Int print ( type ( 3.14 )) # Float print ( type ( 1 + 3j )) # Complex number print ( type ( 'Asabeneh' )) # String print ( type ([ 1 , 2 , 3 ])) # List print ( type ({ 'name' : 'Asabeneh'})) # Dictionaries Print( type ({ 9.8 , 3.14 , 2.7 })) # set up Print( type (( 9.8 , 3.14 , 2.7 ))) # tuple
To run a python file, check the following figure. You can run the python file by running the green button on Visual Studio Code or by typing python helloworld.py in the terminal.
You are awesome. You have just completed the challenge of day 1 and are moving towards greatness.
Day 2 - variables, built-in functions
2.1 built in functions
In python, we have many built-in functions. Built in functions are available to you globally, which means you can use built-in functions without importing or configuring them. Some of the most commonly used python built-in functions are as follows: 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 a detailed list of python built-in functions taken from python documentation.
Let's open the Python shell and start using some of the most common built-in functions.
Let's practice more by using different built-in functions
As can be seen from the terminal above, Python has reserved words. We do not use reserved words to declare variables or functions. We will introduce variables in the next section.
I believe you are now familiar with built-in functions. Let's do the built-in function exercise again, and we will continue to the next section.
2.2 variables
Variables store data in computer memory. Mnemonic variables are recommended in many programming languages. Mnemonic variables are variable names that are easy to remember and associate. A variable is the memory address where data is stored. Variables cannot be named with numbers, special characters, or hyphens. Variables can have a short name (e.g. x, y, z), but more descriptive names (first name, last name, age, country / region) are strongly recommended.
Python variable name rule
- Variable names must start with letters or underscore characters
- Variable names cannot start with numbers
- Variable names can only contain alphanumeric characters and underscores (Az, 0-9, and)
- Variable names are case sensitive (FIRSTNAME, FIRSTNAME, FIRSTNAME, and FIRSTNAME are different variables)
Let's set a valid variable name
name lastname Age country city name lastname capital_city _if #If we want to use reserved words as variables year_2021 2021 year current_year_2021 Year of birth No. 1 Quantity 2
Invalid variable name
name name first $name Number 1 1 number
We will use the standard Python variable naming style adopted by many Python developers. Python developers use the snake_case variable naming convention. For variables that contain multiple words (such as first_name, last_name, engine_rotation_speed), we use the underscore character after each word. The following example is a standard variable naming example. When the variable name exceeds one word, it needs to be underlined.
When we assign a data type to a variable, it is called a variable declaration. For example, in the following example, my name is assigned to the variable first_name. The equal sign is the assignment operator. Assignment means storing data in variables. The equal sign in Python is different from the equal sign in mathematics.
example:
#stay Python variable FIRST_NAME = 'Asabeneh' surname = 'Yetayeh' country = 'Finland city = 'Helsinki' Age = 250 is_married = really skill = [ 'HTML' ,'CSS' ,'JS' ,'camp',' Python' ] person_info = { 'firstname' : 'Asabeneh' , 'lastname' : 'Yetayeh' , 'country' : 'Finland', 'city' : 'Helsinki' }
Let's use the print() and len() built-in functions. The print function takes an unlimited number of parameters. Parameters are values that we can pass or put in function parentheses. See the following example.
example:
print ( 'Hello, World!' ) # Text Hello, World! Is a parameter print ( 'Hello' , ',' , 'World' , '!' ) # It can accept multiple parameters, and four parameters have been passed print ( len ( 'Hello, World!' )) # It only needs one argument
Let's print and find the length of the variable declared at the top:
example:
Print('Name length:',first_name) Print('Name length:',len(first_name)) Print('surname:',last_name) Print('Last name length:',len(last_name)) Print('country:',(country) Print('city:',City) Print('Age:',Age) Print('Married:' , is_married ) Print( 'skill: ' ,skill) Print( 'personal information: ' , person_info )
2.3 declare multiple variables on one line
You can also declare multiple variables on 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('name:',FIRST_NAME) Print('Last name:',(last name) Print('country:',(country) Print('Age:',Age) Print('Married:',is_Married)
Use the input() built-in function to get user input. Let's assign the data obtained from the user to the first_name and age variables.
example:
first_name = input ( 'What's your name?' ) age = input ( 'How old are you?') Print (name) Print (age)
2.4 data type
There are many data types in Python. To identify the data type, we use the type built-in function. I want you to focus on a good understanding of the different data types. When it comes to programming, it's all about data types. I introduced data types at the beginning, and it came again, because each topic is related to data types. We will cover data types in more detail in their respective sections.
2.5 checking data types and conversions
- Check data type: to check the data type of some data / variables, we use type
Example:
# Different python data types # Let's declare variables of different data types first_name = 'Asabeneh' # str last_name = 'Yetayeh' # str country = 'Finland' # str city = 'Helsinki' # str age = 250 # int, this is not my real age. Don't worry # Print type 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 up
- Conversion: converts one data type to another. We use int (), float (), str (), list, set
When we perform arithmetic operations, string numbers should first be converted to int or float
, otherwise an error will be returned. If we connect a number to a string, the number should first be converted to a string. We will discuss concatenation in the 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']
2.6 figures
Numeric data types in Python:
- Integer: integer (negative, zero and positive) number examples:... - 3, - 2, - 1, 0, 1, 2, 3
- Examples of floating point numbers (decimal numbers):... - 3.5, - 2.25, - 1.0, 0.0, 1.1, 2.2, 3.5
- Plural examples: 1 + j, 2 + 4j, 1 - 1j
🌕 You are wonderful. You have just completed the challenge of day 2, and you are two steps ahead on the road to greatness.
Day 3 - Operator
3.1 Boolean
A Boolean data type represents one of two values: True or False. Once we start using comparison operators, the use of these data types will be clear. Unlike JavaScript, the first letter T of True and F of False should be capitalized.
Example:
Print (true) Print (false)
3.2 operator
The Python language supports many types of operators. In this section, we will focus on several of them.
3.3 assignment operator
Assignment operators are used to assign values to variables. Let's take = as an example. The equal sign in mathematics means that two values are equal, but in Python, this means that we store a value in a variable, which we call assignment or assignment to a variable. The following table shows the different types of Python assignment operators.
3.4 arithmetic operators:
- Addition (+): a + b
- Subtraction (-): a - b
- Multiplication (*): a * b
- Division (/): a / b
- Modulus (%): a% B
- Floor division (/ /): a // b
- Exponentiation (* *): a ** b
3.5 arithmetic operators
Example: integer
# Arithmetic operations in Python # integer print ( 'Addition: ' , 1 + 2 ) # 3 print ( 'Subtraction: ' , 2 - 1 ) # 1 print ( 'Multiplication: ' , 2 * 3 ) # 6 print ( 'Division: ' , 4 / 2 ) # The 2.0 Division in Python gives floating point numbers print ( 'Division: ' , 6 / 2 ) # 3.0 print ('Division: ' , 7 / 2 ) # 3.5 print ( 'Division without the remainder: ' , 7 // 2) # 3, give no floating point number or no remainder Print( 'Division without the remainder: ' , 7 / / 3 ) # 2 print ( 'Modulus: ' , 3 % 2 ) # 1. Give the remainder print ( 'Exponentiation: ' , 2 ** 3 )# 9 means 2 * 2 * 2
Example: floating point number
# Floating point number print ( 'Floating Point Number, PI' , 3.14 ) print ( 'Floating Point Number, Gravity' , 9.81 )
Example: plural
# complex print ( 'Complex number: ' , 1 + 1j ) print ( 'Multiplying complex numbers: ' ,( 1 + 1j ) * ( 1 - 1j ))
Let's declare a variable and assign a numeric data type. I'll use single character variables, but remember not to get into the habit of declaring such variables. Variable names should always be mnemonics.
example:
# First declare the variable at the top a = 3 # a is the variable name and 3 is the integer data type b = 2 # b is the variable name and 3 is the integer data type # Arithmetic operation and assign the result to the variable total = a + b diff = a - b product = a * b division = a / b remainder = a % b floor_division = a // b index = a ** b # I should use sum instead of total, but sum is a built-in function - try to avoid overwriting built-in functions print ( total ) # If you don't mark your print with some strings, you never know where the result is 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==') # Declare values and organize them together num_one = 3 num_two = 4 # Arithmetic operation 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 # Use label Print value print ( 'total:' , total ) print ( 'difference:' , diff ) print ( 'product:' , product ) print ( 'division:' , div ) print ( 'remainder:' , remason )
Let's start connecting points and start using calculations we know (area, volume, density, weight, perimeter, distance, force).
example:
# Calculate the area of a circle radius = 10 # Radius of circle area_of_circle = 3.14 * radius ** 2 # Two * symbols denote exponents or powers print ( 'Area of a circle:' , area_of_circle ) # Calculate the area of the rectangle length = 10 width = 20 area_of_rectangle = length * width print ( 'Area of rectangle:' , area_of_rectangle ) #Calculate the weight of the object Quality of = 75 gravity = 9.81 weight = quality * gravity Print (weight“ N") #Add the weight of the unit # Computational liquid Density of mass= 75 # kg . volume = 0.075 # cubic metre density = quality / volume # 1000 Kg/m^3
3.6 comparison operators
In programming, we compare values. We use comparison operators to compare two values. We check whether one value is greater than or less than or equal to other values.
Example: comparison operator
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 ) # Really, because 3 doesn't equal 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 # Compare sth. to give true or false Print('really==True:',really == (true) Print('really==False:',really == (false) Print('false==False:',false == (false)
In addition to the above comparison operators, Python uses:
- Is: returns true if two variables are the same object (x is y)
- Is not: returns true if two variables are not the same object (x is not y)
- In: returns True if the query list contains an item (x in y)
- not in: returns True if the queried list does not have an 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 string print ( 'B in Asabeneh' , 'B' in 'Asabeneh' ) # False - no uppercase B print ( 'coding' stay 'coding for all' ) # True - because encoding all has the word coding print ( 'a in an:' , 'a' in 'an' ) # True print ( '4 is 2 ** 2:' , 4 is 2 ** 2 ) # really
3.7 logical operators
Unlike other programming languages, python uses the 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, not True gives false print (not True ) # False - negative, the not operator changes true to false print ( not False ) # True print ( not not True ) # True print ( not not False ) # False
🌕 You have unlimited energy. You have just completed the challenge of day 3, and you are three steps ahead on the road to greatness.
Day 4 - string
Text is a string data type. Any data type written as text is a string. Any data under single, double, or three quotation marks is a string. There are different string methods and built-in functions to handle string data types. To check the length of a string, use the len() method.
4.1 create string
letter = 'P' # A string can be a single character or a bunch of text print ( letter ) # P print ( len ( letter )) # 1 greeting = 'Hello, World!' # Strings can use single or double quotation marks "Hello, World!" Print (greetings) #Hello, world! print ( len ( greeting )) # 13 sentence = "I hope you enjoy it Python 30 days of challenge" print ((sentence)
Multiline strings are created by using triple single quotation marks ('') or triple double quotation marks (''). See the following example.
multiline_string = '''I am a teacher and like teaching. I find nothing more valuable than empowering people. That's why I created a 30 day python.''' print ( multiline_string ) # Another way to do the same thing multiline_string = """I am a teacher and like teaching. I don't find anything more valuable than empowering people. This is what I created for 30 days Python The reason for this.""" print ( multiline_string )
4.2 string connection
We can concatenate strings together. Merging or concatenating strings is called concatenation. See the following example:
first_name = 'Asabeneh' last_name = 'Yetayeh' space = ' ' full_name = first_name + space + last_name print ( full_name ) # Asabeneh Yetayeh # Use the len() built-in function to check the length of the string print ( len ( first_name )) # 8 Print( len ( last_name )) # 7 Print( len ( first_name ) > len (last_name )) # really Print( len ( full_name )) # 16
4.3 escape sequence in string
In Python and other programming languages, \ followed by a character is an escape sequence. Let's look at the most common escape characters:
- \n: Line feed
- \t: Tab indicates (8 spaces)
- \: backslash
- ': single quotation mark (')
- ": double quotation marks (")
Now, let's look at the use of the above escape sequence through an example.
print ( 'I hope everyone likes it Python Challenge.\n Are you?' ) # Newline character print ( 'Days \t Topics \t Exercises' ) # Add tab spaces or 4 spaces print ( 'Day 1 \t 3 \ t 5' ) Print( 'Day 2 \t 3 \t 5' ) Print( 'Day 3 \t 3 \t 5' ) Print( 'Day 4 \t 3 \t 5' ) print ( 'This is a backslash symbol ( \\ )' ) # Write a backslash print ( 'In every programming language, it takes\" Hello, World! \" ' ' ) # Write a double quotation mark inside a single quotation mark #output I hope everyone is appreciated Python Challenges. It's you? Days Topics practice 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 takes“ Hello, World!"start.
4.4 string formatting
Legacy string format (% operator)
There are many ways to format strings in Python. In this section, we will introduce some of them. The '%' operator is used to format a set of variables contained in tuples (fixed size lists), as well as a format string containing ordinary text and parameter specifiers, special symbols such as "% s", "d", "f", “%.number of numbersf”.
- %s - string (or any object with a string representation, such as a number)
- %d - integer
- %f - floating point number
- '%. number of digitsf' - floating point number with fixed precision
#String only FIRST_NAME = 'Asabeneh' surname = 'Yetayeh' language = 'Python of 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 = 'Radius %d The area of the circle is %.2f.' % ( radius , area ) # 2 refers to the two significant digits after the point python_libraries = [ 'Django of'bottle','NumPy of','Matplotlib' ,'panda' ] formated_string = 'Here is Python Library:%s'of %(python_libraries) Print( formated_string)#"Here is Python library:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"
New style string format (str.format)
This format was introduced in Python version 3.
FIRST_NAME = 'Asabeneh' surname = 'Yetayeh' language = 'Python of formated_string = "I{} {}. I teach {}'. Format (first name, last name, language) Print (format 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 )) # Limit to two decimal places 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 = 'Radius {} The area of the circle is {:.2f}.' . format ( radius , area ) # 2 decimal places Print( formated_string )
String interpolation / f-Strings (Python 3.6 +)
Another new string format is string interpolation, f-strings. Strings start with F, and we can inject data at the corresponding position.
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 } ' )
4.4 Python string as character sequence
Python strings are sequences of characters and share their basic access methods with other sequences of Python ordered objects (lists and tuples). The easiest way to extract individual characters from strings (and individual members in any sequence) is to unpack them into corresponding variables.
Unpacking character
language = 'Python' a,b,c,d,e,f = language # unpacking sequence characters into variables print(a) # P print(b) # y print(c) # t print(d) # h print(e) # o print(f) # n
Accessing characters in a string by index
In programming, counting starts from zero. Therefore, the index of the first letter of the string is zero, and the last letter of the string is the length of the 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 at the right end, we can use a negative index. - 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 ] # Start with zero index, up to 3 but not including 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 ) # dear
Reverse string
We can easily reverse strings in python.
to greet = 'Hello, world! Print (greetings)[:: - 1 ])# !dlroW ,olleH
Skip characters when slicing
By passing the step parameter to the slice method, you can skip characters when slicing.
language = 'Python' pto = language [ 0 : 6 : 2 ] # print ( pto ) # Pto
4.5 string method
There are many string methods that allow us to format strings. See some string methods in the following examples:
- Uppercase (): converts the first character of a string to uppercase letters
Challenge = "30DaysOfPython" Print (challenge. Leverage)#"30DaysOfPython"
- count(): returns the number of occurrences of substrings in a string, count(substring, start =..., end =...). Start
Is the starting index of the count, and end is the last index to count.
Challenge = '30DaysOfPython' Print (challenge) count('Y' ))#3 Print (challenge) count('Y' ,7,14))#1, Print (challenge) count('day'))# 2`
- End switch(): checks whether the string ends with the specified end
Challenge = '30DaysOfPython' Print (challenge) endsWith('open')) #really Printing (challenge) endsWith('ash')) #false
- expandtabs(): replaces tabs with spaces. The default tab size is 8. It accepts the tab size parameter
Challenge ='thirty\tdays\tof\tpython' Print (challenge). expandtabs()) #"30 "Days" Print (challenge). expandtabs(10))#"30 "Days"
- find(): returns the index of the first occurrence of the substring. If it is not found, it returns - 1
Challenge = '30DaysOfPython' Print (challenge). Find('Y' )) #16 Print (challenge). Find('day'))#17
- rfind(): returns the index of the last occurrence of the substring. If it is not found, it returns - 1
Challenge = '30DaysOfPython' Print (challenge). RFIND('Y' )) #5 Print (challenge). RFIND('day'))#1
- format(): Set
first_name = 'Asabeneh' last_name = 'Yetayeh' age = 250 job = 'teacher' country = 'Finland' sentence = 'I am{} {}. I am a {}. I have {} Years old. I live in {}. ' . Format( FIRST_NAME,Last name, age, occupation, country) Print (sentence)#I Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland. radius = 10 pi = 3.14 area = pi * radius ** 2 result = 'Radius {} The area of the circle is {}'. format ( str ( radius ), str ( area )) print ( result ) #The area of a circle with a radius of 10 is 314
- index(): returns the lowest index of the substring. The additional parameters represent the start and end indexes (0 and string length - 1 by default). If the substring is not found, an error will be thrown
valueError.
Challenge = '30DaysOfPython' SUB_STRING = 'DA' Print (challenge index)( SUB_STRING)) #7 Print (challenge index)( SUB_STRING,9)) #error
- rindex(): returns the highest index of the substring. Additional parameters indicate the start and end indexes (default 0 and string length - 1)
Challenge = '30DaysOfPython' SUB_STRING = 'DA' Print (challenge). RINDEX(SUB_STRING)) #8 Print (challenge). RINDEX(SUB_STRING,9)) #error
- isalnum(): check alphanumeric characters
Challenge = '30DaysOfPython' Print (challenge) characters isalnum()) #really Challenge = '30DaysPython' Print (challenge) characters isalnum()) #really Challenge = "30DaysOfPython" Print (challenge) characters isalnum()) #False, space is not an alphanumeric character Challenge = '30DaysOfPython2019 of' Print (challenge) characters isalnum()) #false
- isalpha(): checks whether all string elements are alphabetic characters (AZ and AZ)
Challenge = '30DaysOfPython' Printing (challenge). Thus isalpha()) #False, space is excluded again Challenge = 'ThirtyDaysPython' Printing (challenge). Thus isalpha()) #really NUM = '123' Print( NUM. thus isalpha( )) # error
- isdecimal(): checks whether all characters in the string are decimal (0-9)
Challenge = '30DaysOfPython' Print (challenge). isdecimal()) #false Challenges = '123' Print (challenge). isdecimal()) #really Challenge = ' \ u00B2 ' Print (challenge). ISDIGIT()) #false Challenges = '12 3' Print (challenge). isdecimal()) #False, space not allowed
- isdigit(): check whether all characters in the string are numbers (0-9 and other unicode characters for numbers)
Challenge = '30DaysOfPython' Print (challenge). ISDIGIT()) #false Challenges = '30' Print (challenge). ISDIGIT()) #really Challenge = ' \ u00B2 ' Print (challenge). ISDIGIT()) #really
- isnumeric(): check whether all characters in the string are numeric or numeric related (like isdigit()), and only accept more symbols, such as ½)
NUM = '10' Printing( NUM. ISNUMERIC()) #really NUM = ' \ u00BD ' #½ Print( NUM. ISNUMERIC()) #really NUM = '10 0.5' Print( NUM. ISNUMERIC()) #false
- isidentifier(): checks for a valid identifier -- it checks whether a string is a valid variable name
Challenge = '30DaysOfPython' Print (challenge). isIdentifier Different () #False, because it starts with a number Challenge = '30_days_of_python' Print (challenge). isIdentifier Different () #really
- islower(): checks whether all alphabetic characters in the string are lowercase
Challenge = "30 days of python" Print (challenge). islower Judgment ()) #really Challenge = "30 days of python" Print (challenge). islower Judgment ()) #false
- isupper(): checks whether all alphabetic characters in the string are capitalized
Challenge = "30 days of python" Print (challenge). isupper()) #false Challenges = '30 days of python Print (challenge). isupper()) #really
- join(): returns a connected string
web_tech = [ 'HTML' , 'CSS' , 'JavaScript' , 'React' ] result = ' '. join ( web_tech ) print ( result ) # 'HTML CSS JavaScript React' web_tech = [ 'HTML' , 'CSS' , 'JavaScript' , 'React' ] result = '# '. join ( web_tech ) print ( result ) # 'HTML# CSS# JavaScript# React'
- strip(): deletes all given characters from the beginning and end of the string
Challenge = '30 days of python' print ( challenge . strip ( 'noth' )) # 'thirty days of py '
- replace(): replaces the substring with the given string
Challenge = "30 days of python" Print (challenge. Replace)(“ Python","Code "))#"30 "Day code"
- split(): splits the string, using the given string or space as the separator
Challenge = "30 days of python" Print (challenge. Split ())#["30","Days "“ of","Python"] Challenge = "30,God,, Python" Print (challenge). Split( ', ' )) # ['30', 'Day', 'of', 'python']
- title(): returns a Title Case string
Challenge = "30 days of python" Print (challenge title) #Python30 day
- swapcase(): converts all uppercase characters to lowercase and all lowercase characters to uppercase
Challenge = '30 days of python' Print (challenge) swapCase()) # Python 30 days Challenge = '30 days of python' Print (challenge) swapCase()) # Python 30 days - startswith(): Checks whether the string starts with the specified string ```python Challenge = "30 days of python" Print (challenge). startswith("30")) #really Challenge = '30 days of python' Print (challenge). startswith('30')) #false
🎉 congratulations! 🎉 You are an extraordinary person and you have extraordinary potential. You have just completed your fourth day of study.
There are a lot of words shared today. As a sequel update, you are interested in learning the following contents. Remember to pay attention to me. Your three companies are the driving force for my continuous output. Thank you.