Basic Python grammar for beginners

Introduction

I had a chance to touch Python, so I tried to summarize the basic grammar of Python as a review of myself!

table of contents#

[1. Output](# 1 output) [2. Variable](# 2 variable) [3. Combine strings](# 3 Combine strings) [4.if statement](# 4if statement) [5.for statement](# 5for statement) [6.while statement](# 6while statement) [7. break, continue with for and while](break-continue with # 7 for and while) 8.list [9. Dictionary](# 9 dictionary)

1. Output

You can print the value in () with print (). The string is displayed by enclosing it in (') single quotes or (") double quotes.


print('123')
>>>123
print("123")
>>>123

The numbers do not need to be enclosed in single quotes.

print(123)
>>>123

In Python programs, 123 is treated as a number and '123' is treated as a string. For example, the number (1 + 1) is 2, but the string ('1' + '1') is It will be '11' because it will be a combination of strings.

print(1+1)
>>>2
print('1'+'1')
>>>11

2. Variable

You can assign a value to a variable with ** variable name = value **. Str if the value is enclosed in single quotes. If you enter an integer number, it will be treated as an int. Also, if you want to check the type of a variable in Python, use the type function

mystr = 'hello'
print(type(mystr))
>>> <type'str'>

myint = 123
print(type(myint))
>>> <type'int'>

You can call the value of a variable by putting the variable name in print ().

mystr = 'hello'
print(mystr)
>>>hello

3. String concatenation

You can combine strings with the (+) symbol.

mystr = 'hello'
print('Hello' + 'Python')
print(mystr + 'Python')
>>>Hello Python
>>>helloPython

When combining a character string and a numerical value, if you combine them as they are, an error will occur.

myint = 123
print('The numbers are' + myint)
>>>TypeError:can only concatenate str (not "int") to str

It is possible to combine int type and str type and output by converting the type with the str () function.

myint = 123
print('The numbers are' + str(myint))
>>>The number is 123

You can also combine strings and numbers by using (,). At that time, a space will be inserted between the combinations, so it is necessary to specify the delimiter with the sep of the print () option.

myint = 123
print('The numbers are' , myint)
>>>The number is 123

myint = 123
print('The numbers are' , myint , sep='')
>>>The number is 123

4. if statement

A simple if statement looks like this:

if conditional expression:
Process 1
Process 2
Process 3 ← Error occurs

※important point -Add a (:) colon at the end of the if line ・ Align the indentation of processing If you write a sentence with incorrect indentation, an error will occur.

You can specify multiple conditions by using ** elif **.

if first condition:
Processing when the first condition is satisfied
elif second condition:
Processing when the second condition is satisfied
elif third condition:
Processing when the third condition is satisfied
else:
Processing when none of the conditions are met

5. for statement

The syntax of the for statement is as follows.

for variable in a collection of data:
processing

The for statement is a flow of extracting data one by one from a collection of data. For example, the process of extracting and displaying each character from the character string'Hello' is as follows.

for char in 'Hello':
    print(char)
>>>H
>>>e
>>>l
>>>l
>>>o

You can write a process that loops a specified number of times by using the ** range function **.

for i in range(3):
    print(i)
>>>0
>>>1
>>>2

In the above case, it is a process that loops 3 times from i = 0. If you want to loop from i = 1, specify the loop range.

for i in range(1,3):
    print(i)
>>>1
>>>2
>>>3

#1~If you want to loop up to 100
for i in range(1,100)
    print(i)

・ List loop processing

The list is explained in detail in ** [here](# 8list) **.

You can retrieve the contents of the list one by one by putting the variables of the list in the data collection part of the for statement.

list = ['item1', 'item2', 'item3']
for item in list:
    print(item)
>>>item1
>>>item2
>>>item3

The above code assigns the contents of the list to the variable item one by one and displays it.

6. While statement

The while statement is the same iterative process as the for statement, but the for statement checks the information of the data collection one by one and processes up to the last element, while the while statement processes while the condition is satisfied. I repeat.

#val until val reaches 4=Add 1 to 0.
val = 0
while val < 4:
    val += 1
    print(val)
print('val is' + str(val))
>>>1
>>>2
>>>3
>>>4
>>>val is 4

・ Use for and while properly

・ If the number of repetitions is fixed, for statement ・ I don't know how many times to repeat, but if the end condition is clear, a while statement

7. break, continue with for and while

・ Break statement

You can use break to force the iterative process to end.

#break with for statement
list = [1,2,3,4,5]
for i in list:
    if i == 3:
        break
    print(i)
>>>1
>>>2
>>>Repeat processing ends with break

#break with while statement
val = 1 
while val < 10:
    if val == 3:
        break 
    print(val)
    val += 1
>>>1
>>>2
>>>Repeat processing ends with break

・ Continue statement

The continue statement is used when you want to skip processing. Since it is just skipped, the process will continue without stopping.

#continue with a for statement
list = [1,2,3,4,5]
for i in list:
    if i == 2:
        continue
    print(i)
>>>1
>>>3
>>>4
>>>5

#continue in a while statement
val = 0
while val < 5:
    val += 1
    if val == 2:
        continue
    print(val)
>>>1
>>>3
>>>4
>>>5

Since it is continued when the condition of the if statement in the iterative process, the process is skipped in the output part of 2.

8.list# A list is a list of elements in [] separated by (,) commas. It is also possible to enter the value as a variable when creating the list.

list = ['a','b','c']
print(list)
>>>['a','b','c']

a = 10
b = 20
c = 30
list = [a,b,c]
print(list)
>>>[10,20,30]

Elements in list can refer to the element at the specified position with ** list name [index] **.

list = ['a','b','c']
#First element
print(list[0])
#Second element
print(list[2])
>>>a
>>>c

-Adding a value to the list

You can add an element to the end of the list with ** list name.append (additional element) **.

list = ['a','b','c']
list.append('d')
print(list)
>>>['a','b','c','d']

You can add an element at the specified position in the list with ** list name.insert (position, additional element) **.

list = ['a','b','c']
list.insert(1, 'd')
print(list)
>>>['a','d','b','c']

-Remove value from list

You can remove the last element of the list with ** listname.pop () **.

list = ['a','b','c']
list.pop()
print(list)
>>>['a','b']

You can delete the element at the specified position in the list with ** list name.pop (index) **.

list = ['a','b','c']
list.pop(1)
print(list)
>>>['a','c']

・ Update list values

You can update the element at the specified position in the list with ** list name [index] = value you want to change **.

list = ['a','b','c']
list[1] = 'x'
print(list)
>>>['a','x','c']

9. Dictionary

A dictionary is data that has a key and its corresponding value. A dictionary object combines keys and values with a colon (:) and separates multiple elements with a comma (,), such as {key: value, key: value, ...}. You can retrieve the value corresponding to the dictionary key with ** dictionary name [key] **.

dict = { 'apple':1, 'orange':2, 'banana':3 }
print(dict['apple'])
>>>1

・ Update dictionary value

You can update the value of the specified key with ** dictionary name [key] = value you want to update **.

dict = { 'apple':1, 'orange':2, 'banana':3 }
dict['apple'] = 5
print(dict)
>>>{ 'apple':5, 'orange':2, 'banana':3 }

-Delete dictionary values

You can delete the specified key and value with ** del dictionary name [key] **.

dict = { 'apple':1, 'orange':2, 'banana':3 }
del dict['apple'] 
print(dict)
>>>{'orange':2, 'banana':3 }

・ Confirmation of key existence

You can check if the specified key exists in the dictionary by using the ** in operator **.

dict = { 'apple':1, 'orange':2, 'banana':3 }
if 'apple' in dict:
    print('Exists')
else:
    print('do not exist')
>>>Exists

** Dictionary name.get (processing when there is no key, key) ** makes the if statement unnecessary.

#If the key exists
dict = { 'apple':1, 'orange':2, 'banana':3 }
print('apple', dict.get('apple', 'do not exist'), sep='')
>>>apple is 1

#If the key does not exist
dict = { 'apple':1, 'orange':2, 'banana':3 }
print('fruit is', dict.get('fruit', 'do not exist'), sep='')
>>>fruit does not exist

Reference link

https://www.atmarkit.co.jp/ait/articles/1904/02/news024.html https://docs.python.org/ja/3/tutorial/index.html https://www.sejuku.net/blog/24122 http://programming-study.com/technology/python-for/

Recommended Posts

Basic Python grammar for beginners
Python3 basic grammar
[For beginners] Learn basic Python grammar for free in 5 hours!
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar note (4)
Python basic grammar note (3)
Python basic grammar memo
OpenCV for Python beginners
Memo # 4 for Python beginners to read "Detailed Python Grammar"
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
Basic story of inheritance in Python (for beginners)
Learning flow for Python beginners
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python3 environment construction (for beginners)
Python #function 2 for super beginners
Python basic grammar (miscellaneous) Memo (2)
100 Pandas knocks for Python beginners
[Python] Sample code for Python grammar
Python for super beginners Python #functions 1
Python #list for super beginners
~ Tips for beginners to Python ③ ~
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Python Exercise for Beginners # 1 [Basic Data Types / If Statements]
Java and Python basic grammar comparison
Python Exercise for Beginners # 2 [for Statement / While Statement]
Python for super beginners Python # dictionary type 1 for super beginners
Python #index for super beginners, slices
<For beginners> python library <For machine learning>
Python #len function for super beginners
Basic grammar of Python3 system (dictionary)
Beginners use Python for web scraping (1)
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
2016-10-30 else for Python3> for:
python [for myself]
INSERT into MySQL with Python [For beginners]
RF Python Basic_01
[Python] Minutes of study meeting for beginners (7/15)
Roadmap for beginners
Let's put together Python for super beginners
Basic Python writing
[Basic grammar] Differences between Ruby / Python / PHP
Linux operation for beginners Basic command summary
Python grammar notes
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
[Python] Read images with OpenCV (for beginners)
WebApi creation with Python (CRUD creation) For beginners
RF Python Basic_02
Beginners practice Python