Let's actually write the program. The meaning of each code will be explained in the following chapters, so First, let's execute the program that we actually wrote.
Create a file with the name ** odd_or_even.py ** and write the following program. Note the indentation that is characteristic of Python. Indentation can be tabs or half-width spaces, but be careful of the number when using spaces.
odd_or_even.py
def odd_or_even():
for i in range(1,6):
if i % 2 != 0:
print("{0} is odd".format(i))
else:
print("{0} is even".format(i))
if __name__ == "__main__":
odd_or_even()
If Python is installed correctly, running the program will produce results similar to the following:
1 is odd 2 is even 3 is odd 4 is even 5 is odd
This program is a program that determines whether the values from 1 to 5 are odd or even. Translated into Japanese, the above program performs the following processing.
From the next page, we'll start with a description of Python notation. But before that, keep in mind the following for future learning:
print The statement to output characters in a program is the print statement. Run the following program to understand how to use the print statement.
print_explain.py
print("display statement")
print("display statement {0}".format("string"))
print("display {0} {1} {2}".format(1,"a","abc"))
A comment is a comment inserted in human language (Japanese or English) in the source code. It is ignored when the computer does the work, so you are free to insert statements. When someone else reads a program you write, the code alone may not tell you what the program is meant to be. If you add a comment at that time, it will help the other person to understand your intention. Also, if there is a program that you do not want to run temporarily, you may comment it. If you want to put a line in a comment state, write "#" at the beginning. The following program outputs "taro" and "saburo", but does not output "jiro".
comment_explain.py
print("taro")
#print("jiro")
print("saburo")
If you want to comment out multiple lines at once, enclose the statement in three double quotes (or single quotes).
multi_comment_explain.py
print("1")
#print("2")
print("3")
print("4")
'''
print("5")
print("6")
'''
print("7")
print("8")
"""
print("9")
print("10")
"""
Make good use of your comments.
Please execute the following program. I think you will get an error.
display_japanese_ERROR.py
print("Hello World")
If you want to output Japanese in Python, add the following code to the first line.
display_japanese.py
# -*- coding: utf-8 -*-
print("Hello World")
I think it will be output correctly. If you want to input / output Japanese with Python, go to Character code and utf-8. You need to specify that you are using /UTF-8.html).
Next: Python Basic Course (4 Numerical Type / String Type)
Recommended Posts