Python Basic Grammar Memo (Part 1)

Display a string

Characters can be output (displayed) by using "print". The characters written in () after print are output to the screen called "Console".

print('Hello World')

The string must be enclosed in single quotes "'" or double quotes "" ", and the output will be the same regardless of which one is enclosed. If it is not enclosed in either, an error will occur.

#print('Comment out')

You can write a comment in the code by writing "#" at the beginning of the line.

Numerical value

Addition and subtraction are possible using the same symbols "+" and "-" as in mathematics, and all numbers and symbols are written in half-width characters. If you enclose it in quotation marks like "'9 + 3'", it will be interpreted as a character string and "9 + 3" will be output as it is.

#Please output the value obtained by adding 3 to 9
print( 9 + 3)

# 「9 +Please output "3" as a character string
print('9 + 3')
Other calculations

Multiplication is represented by "*", division is represented by "/", and the remainder of division can be calculated by "%".

# Please output the value obtained by dividing 9 by 2.
print(9 / 2)

# Please output the value obtained by multiplying 7 by 5.
print(7 * 5)

# Please output the remainder when 5 is divided by 2.
print(5 % 2)
variable

Variables are defined by "variable name = value". Variable names do not need to be quoted.

# Substitute the string "hogehoge" for the variable name
 name = "Hogehoge"

# Output the value of the variable name
print(name)

# Substitute the number 8 for the variable number
number = 8

# Output the value of the variable number

print(number)
How to use variables

The first letter of the variable name cannot be a number. Also, when using a variable name of two or more words such as "user_name", it is necessary to separate words with _ (underscore).

pen_price = 200
pen_count = 8

# Assign the result of multiplying pen_price and pen_count to the variable total_price.
total_price = pen_price * pen_count 

# Please output the value of total_price
print(total_price)
Update the value of a variable

You can overwrite the value of the variable by setting "variable name = new value".

year = 2000
print(year)

# Add 5000 to the variable year and overwrite the variable money
year = year + 20

# Output the value of the variable money
print(year)
Abbreviation

When updating the value of a variable containing a numerical value, it can be omitted.

 #Uninflected word #Abbreviation
y = y + 10        y += 10
y = y - 10        y -= 10
y = y * 10        y *= 10
y = y / 10        y /= 10
y = y % 10        y %= 10
Concatenation of characters

The "+" symbol used in the calculation of numerical values can be used not only for calculation but also for concatenating character strings. In addition, variables and character strings can be concatenated, and variables can be concatenated with each other.

# Substitute the string "python memo" for the variable my_name
 my_name = "python memo"

# Use my_name to concatenate variables and strings and output "I'm a python memo"
 print ("I am" + my_name + "")
Data type

An error occurs when concatenating string types and numeric types with different data types. Changing the data type is called "type conversion". Character strings and numbers can be connected. Use "str" to convert a numeric type to a string type. If you want to convert the string type to the numeric type, use "int".

age = 36
# Please output "I am 36 years old" using age
 print ('I' + str (age) +'I'm old')

count = '20'
# Output the value obtained by adding 1 to count
print(int(count) + 1)
if statement

Write the conditional part of the if statement as "if conditional expression:" Whether or not the processing is in the if statement is determined by indentation. The processing in the if statement is executed when the condition is satisfied.

# Output "x is 80" when x is equal to 80
if x == 80:
 print ('x is 80')

# If y is not equal to 50, print "y is not 50"
if y != 50:
 print ('y is not 50')
 print ('y is 30!')
    
# If the indents are not aligned, it is considered to be out of the if statement.
if y != 50:
 print ('y is not 50')
 print ('y is 30!')
Boolean value

In addition to symbols that compare the equality of values such as == and! =, Comparison operators include symbols that compare the magnitude of values. Large and small comparison symbols such as "<" and ">". "X> y" returns True if x is greater than y and False if x is less. "X <y" is the opposite. The symbols "≧" and "≦" (representing above and below) must be described as> =, <=.

x = 20
# If x is greater than 30, print "x is greater than 30"
if x > 30:
 print ('x is greater than 30')


yen = 400
pen_price = 200
# When the value of yen is greater than or equal to the value of pen_price, output "You can buy a pen".

if yen >= pen_price:
 print ('You can buy a pen')
else:
 print ('not enough money')

elif If you want to define multiple cases where the condition is not satisfied in the if statement, use "elif". At the end of the line: Don't forget the (colon)!

yen = 100
pen_price = 100

if yen > pen_price:
 print ('You can buy a pen')
# If the values of the variables are equal, please output "You can buy a pen, but the money will be 0"
elif yen == pen_price:
 print ('You can buy a pen, but the money will be 0')

else:
 print ('not enough money')
Multiple conditional expressions

"And" ... When "Condition 1 and Condition 2 are satisfied", write as "Condition 1 and Condition 2".

“Or” ・ ・ ・ When “Condition 1 or Condition 2 is satisfied”, write as “Condition 1 or Condition 2”.

"Not" ... The condition can be denied.

a = 20
# If a is 10 or more and 30 or less, output "a is 10 or more and 30 or less".
if 10 <= a <= 30:
 print ('x is 10 or more and 30 or less')
b = 60
# If b is less than 10 or greater than 30, print "b is less than 10 or greater than 30"
if b < 10 or b > 30:
 print ('b is less than 10 or greater than 30')
c = 55
# If c is not 77, output "c is not 77"
if not c == 77:
 print ('c is not 77')
input (variable)

"Input" allows you to enter characters into the console when you execute code and receive the entered values. "Variable = input ('character string you want to display on the console')" The value entered in the console is assigned to the variable.

banana_price = 200

# Take the input using input and assign it to the variable input_count
 input_count = input ('Please enter the number of bananas to buy:')

# Substitute input_count as a number (an error will occur if you do not specify the number form when substituting)

count = int(input_count)
total_price = banana_price * count

 print ('The number of bananas to buy is' + str (count) +'The number of bananas')
 print ('Payment amount is' + str (total_price) +'Yen')
list

Something like an array in PHP The list is made like [element 1, element 2, ...], and each value is called an element. Multiple character strings and multiple numbers can be managed as one. If you want to get it, use the list [index number].

# Assign the variable fruits to a list with multiple strings as elements
fruits = ['apple', 'banana', 'orange', 'melon']

# Output the element with index number 0
print(fruits[0])

# Please concatenate the element with index number 2 with the character string and output it (when using a list, int type or str type is not specified)

 print ('I like fruits' + fruits [4] +')
Add or update the list

Update: The element with the index number specified in "List [index number] = value" can be updated. Add ... Add a new element to the end of the list defined in "List.append (value)".

fruits = ['apple', 'banana', 'orange','melon']

# Add the string "strawberry" to the end of the list
fruits.append('strawberry')

# Output the list assigned to the variable fruits
print(fruits)

# Update the element with index number 3 to the string "cherry"
fruits[3] = 'cherry'

# Output the element with index number 3
print(fruits[3])
for statement

By writing "for variable name in list:", the process can be repeated as many times as there are elements in the list.


fruits = ['apple', 'banana', 'orange','melon']

# Use the for statement to extract the elements of the list one by one and output them.
for fruit in fruits:
 print ('I like'fruit'+ fruit +')
dictionary

Associative array in PHP

Create a dictionary like {key 1: value 1, key 2: value 2,…} To retrieve it, write it like a dictionary name [key] using the corresponding "key".

# Assign the dictionary to the variable fruits
 fruits = {'orange':'orange','melon':'melon'}

# Output the value corresponding to the key "melon" in the dictionary fruits
print(fruits['melon'])

# Use the dictionary fruits and output so that "melon means ◯◯"

 print ('melon means'+ fruits ['melon'] +')
Dictionary update and addition

You can update the element by writing dictionary name [key name] = value. You can add a new element to the dictionary by writing "dictionary name [new key name] = value".

fruits = {'apple': 150, 'banana': 250, 'melon': 450}

# Update the value of the key "banana" to the number "350"
fruits['banana'] = 350

# Add the element with the key "cherry" and the value "550" to the dictionary fruits
fruits['cherry'] = 550

# Please output the value of fruits
print(fruits)
Dictionary for statement

The feeling of outputting an associative array in PHP with a for statement You can iterate by writing "for variable name in dictionary:". Retrieve the value using the key name.

 fruits = {'apple':'apple','melon':'melon','orange':'orange'}

# Use the for statement to take out the keys of the dictionary one by one and output "In English, ◯◯ means △△" in the repetition.
for fruit_key in fruits:
 print ('in English' + fruit_key +'means'+ fruits [fruit_key] +')
while statement

A while statement is a process that "repeats the process while a certain condition is met".

y = 20

# Use a while statement to create an iterative process that repeats while "variable x is greater than 0"
while y > 0:
 # Output variable x
    print(x)
 #Subtract 1 from the variable x (infinite loop without this description)
    x = x - 1 

break

You can use break to end the iterative process. Be careful not to forget to add the ":" colon


numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
 # When the variable number is 4, output "4 was found, so the process will end", and then end the process.
    if number == 4:
 print ('4 is found, so process ends')
        break

continue

Only the processing of that week can be skipped. It can be used in the same way in if statements and while statements.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
 # When the value of the variable number is a multiple of 2, skip the iteration (write as a multiple of 2 = split by 2)
    if number % 2 ==  0:
        continue
    
    print(number)

Recommended Posts

Python Basic Grammar Memo (Part 1)
Python basic memo --Part 2
Python basic grammar memo
Python basic memo --Part 1
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Python basic grammar (miscellaneous) Memo (4)
Python3 basic grammar
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic memorandum part 2
Basic Python command memo
Python basic grammar note (4)
Python basic grammar note (3)
Basic Python 3 grammar (some Python iterations)
Python application: Pandas Part 1: Basic
Python installation and basic grammar
Basic Python grammar for beginners
I learned Python basic grammar
Python (Python 3.7.7) installation and basic grammar
Python memo
python memo
python memo
Python memo
Python memo
Python memo
Java and Python basic grammar comparison
Introduction to Ansible Part 2'Basic Grammar'
Basic grammar of Python3 system (dictionary)
Python application: data visualization part 1: basic
Basic Linear Algebra Learned in Python (Part 1)
QGIS + Python Part 2
[Python] Memo dictionary
RF Python Basic_01
python beginner memo (9.2-10)
python grammar check
Flask basic memo
Basic Python writing
★ Memo ★ Python Iroha
[Basic grammar] Differences between Ruby / Python / PHP
[Python] EDA memo
Python 3 operator memo
Python grammar notes
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 series (list, tuple)
Python: Scraping Part 1
[My memo] python
Python3 metaclass memo
Python Basic Memorandum Part 3-About Object Orientation-
RF Python Basic_02
[Python] Basemap memo
Basic grammar of Python3 system (included notation)
Python beginner memo (2)
Python3 Beginning Part 1
[Python] Numpy memo
Python: Scraping Part 2
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"
VBA user tried using Python / R: basic grammar