A Java programmer studied Python. (for, if, while statement)

Why did you decide to study Python?

~~ Qiita I've run out of posts once a week. Any inexperienced programming language was fine. ~~ About last week, the news that "Python finally overtakes Java in the programming language ranking" became a hot topic. At that time, I casually looked at the Python source code, "The format is completely different from Java, PHP, and C # that I have experienced so far ... I can't read ..." "But when it comes to artificial intelligence that is popular now, Python ... I'm interested and would you like to study basic syntax ..." It became. Even in Qiita's tag ranking, I'm always number one on a weekly / monthly basis, and I thought it wouldn't hurt to study.

I think it's the nth brew, but ~~ Qiita Because of the goal of posting once a week ~~ I studied while comparing with Java.

Operation check environment

Hello World! At first, "Hello World!" The output image is

Hello World!

In Java

HelloWorld.java


System.out.println("Hello World!");

With Python

HelloWorld.py


print("Hello world!")

~~ I understand that the delimiter semicolon (;) is unnecessary here. ~~ I told you in the comments.

Python also has a semicolon (;), which is used when writing multiple statements on one line.

x = 10; y = 20; z = 30;
#Action together above
x, y, z = 10, 20, 30

That's why I tried it.

HelloWorld.py


print("Hello world!");print("Hello world!!")

Execution result

Hello world!
Hello world!!

I was able to write a semicolon! Since you taught me so much, I investigated the semicolon in Python.

Looking at the Google Python Style Guide, it seems that it is written as follows.

End the line with a semicolon, and do not use a semicolon to write two instructions on the same line.

As with Java, writing two instructions on the same line is not allowed. Also, it seems that it is not good to end the line with a semicolon.

In Python, I interpreted it as ** "Let's code without using a semicolon" **.

Other than that, the style rules are the same as Java that I've been doing so far.

for statement

Next, I wrote a for statement. The output image is

0
1
2
3
4

In Java, the code below

ForDemo.java


for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Try writing in Python by imitating what you see,

ForDemo1.py


for i in range(0, 5):
print(i)

Execute!

IndentationError: expected an indented block

\(^o^)/ Google search here with "Python syntax"! (slow Take a look at Search results at the top. Excerpt from the linked indent item

In Perl and PHP, blocks (compound sentences) are constructed by enclosing statements in {...}, but in Python, indentation (the number of whitespace characters at the beginning of a line) is important, and indentation is performed with the same number of whitespace characters. The sentence is considered a block. {Omitted} Use four whitespace characters for indentation. Tab characters are considered 1 to 8 whitespace characters so that the indentation is a multiple of 8.

Since the indent acts as a block, you don't have to enclose it in {}. Even if a beginner like myself wrote Python, it may be good that the indentation is aligned.

So put an indent before print (i) in the syntax that gave the error earlier.

ForDemo2.py


for i in range(0, 5):
    print(i)

When you run

0
1
2
3
4

It came out properly. You can also specify a character string after in.

ForDemo3.py


for c in 'Hello':
    print(c)

The execution result is output one character per line,

H
e
l
l
o

The question arose here.

What if a for hoge in array?

Let's verify whether to output one character per line or one word per line.

ForDemo4.py


list = ['Hello', 'World']
for c in list:
    print(c)

The execution result is

Hello
World

It appeared one word per line. Then, if you write a for statement twice, will it output one character per line?

ForDemo5.py


list = ['Hello', 'World']
for c1 in list:
    for c2 in c1:
        print(c2)

The execution result is

H
e
l
l
o
W
o
r
l
d

if statement

Next, about the if statement that is indispensable for conditional branching. Let's write the code written in Java in python.

IfDemo1.java


String str = "blue";
if ("blue".equals(str)) {
    System.out.println("It is a green light.");
} else if ("yellow".equals(str)) {
    System.out.println("It is a yellow light.");
} else {
    System.out.println("It is a red light.");
}

I will write the if statement after seeing various sample codes.

ifDemo1.py


str = "blue"
if str == "blue":
    print("It is a green light.")
elif str == "yellow":
    print("It is a yellow light.")
else:
    print("It is a red light.")

When I run it,

It is a green light.

It worked normally. ~~ At first, I wrote else if and got an error. ~~ What do Python programmers read elif? When I was writing, I wrote Elihu while reading it in my heart. I think it's cool like an elf swordsman. (Noisy

What about OR, AND, NOT?

The existence of OR, AND, and NOT is indispensable for writing complicated conditional branches.

IfDemo2.java


int i = 0;
if (i == 0 || i < 0) {
    System.put.println("0 or less");
} else if (50 <= i && i <= 100) {
    System.out.println("50 or more and 100 or less");
} else if (!i == 0) {
    System.out.println("Not 0");
}

Again, I will write after seeing various sample codes.

IfDemo2.py


i = 0
if i == 0 or i < 0:
    print("0 or less")
elif 50 <= i and i <= 100:
    print("50 or more and 100 or less")
elif not i == 0:
    print("It's not 0.")

The execution result is

0 or less

As I told you in the comments, it is also possible to describe the elif part as follows. The number of input characters is small, and it is quite good because you can grasp the conditions of what kind of content at a glance.

IfDemo3.py


i = 50
if i == 0 or i < 0:
    print("0 or less")
elif 50 <= i <= 100::
    print("50 or more and 100 or less")
elif not i == 0:
    print("It's not 0.")

Execution result

50 or more and 100 or less

Second, Python doesn't need a block definition with {}, I didn't know if the conditional expression could be enclosed in (), so I tried it.

IfDemo4.py


i = 1
if (i == 1) or (i >= 2 and i < 3):
    print("OK!")

The execution result is

OK!

I was able to add (). Regarding conditional branching, it seems that the same idea as Java, such as prioritizing, can be applied.

while statement

I think that the basics of loop processing are for statement and while statement, so I also wrote a while statement. The output image is the same as the for statement,

0
1
2
3
4

When I write it in Java,

WhileDemo.java


int i = 0;
while(i < 5) {
    System.out.println(i);
    i++;
}

Let's write it in Python by imitating the sample code.

WhileDemo1.py


i = 0
while i < 5:
    print(i)
    i++

I got an error in i ++. Upon examination, it seems that Python does not have an increment operator like i ++. Instead, it uses a method called ** cumulative substitution ** as shown below.

WhileDemo2.py


i = 0
while i < 5:
    print(i)
    i += 1

The execution result is as expected

0
1
2
3
4

Since there is no increment, it seems that there is no decrement. Decrement is in the same format as increment,

WhileDemo3.py


i = 4
while 0 <= i:
    print(i)
    i -= 1

Execution result

4
3
2
1
0

Impressions of trying

Since it is not enclosed in {}, there is no line with only}. Therefore, the number of lines of source code is quite small. From the impression that else if is written as elif, I think that the number of input characters is also small. With this, not only machine learning but also web applications and games can be created, so there is demand!

However, I'm not used to the fact that the delimiter semicolon (;) is unnecessary. I will attach a semicolon with momentum.

「PYPL PopularitY of Programming Language」, If you look at the result properly, The drop in PHP is so great that I think it's better to throw away PHP and shift to Python. I am very anxious because I have no idea what the future of Java is.

I don't have anything I want to make specifically using Python, so I'm wondering if I'll continue studying Python ...

Recommended Posts

A Java programmer studied Python. (for, if, while statement)
A Java programmer studied Python. (About type)
A Java programmer studied Python. (About functions (methods))
A Java programmer studied Python. (About the decorator)
[Super basic] Compare Python, Java and JavaScript (variable, if statement, while statement, for statement)
Python Exercise for Beginners # 2 [for Statement / While Statement]
Python if statement
[Python] if statement
Python basics ② for statement
Python basic if statement
[Python] for statement error
Python list, for statement, dictionary
[Python / PyQ] 4. list, for statement
Introduction to Python For, While
[Python] Iterative processing (for, while)
How to define multiple variables in a python for statement
Turn an array of strings with a for statement (Python3)
[Python] What is a with statement?
[Introduction to Python] How to use the in operator in a for statement?
Python for statement ~ What is iterable ~
[python] Correct usage of if statement
[Python] Multiplication table using for statement
[Python] File operation using if statement
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Python of Hikari-] Chapter 05-09 Control syntax (use of for statement and while statement properly)
A useful note when using Python for the first time in a while
[Introduction to Udemy Python3 + Application] 33. if statement
Let's create a virtual environment for Python
Change the list in a for statement
[Mac] Building a virtual environment for Python
Make Qt for Python app a desktop app
Get a token for conoha in python
A tool for easily entering Python code
Building a Python development environment for AI development
A textbook for beginners made by Python beginners
Turn multiple lists with a for statement at the same time in Python
while statement
[Introduction to Python] How to get the index of data with a for statement
[Python, Scala] Do a tutorial for Apache Spark
I made a python dictionary file for Neocomplete
Python basics (variables, types, operators, if statements, for statements)
Get a ticket for a theme park with python
Create a LINE BOT with Minette for Python
I wrote a class in Python3 and Java
Procedure for creating a LineBot made with Python
Python with Progate (dictionary, while statement, break, continue)
Why I'm a Java shop and start Python
[Introduction to Udemy Python3 + Application] 40.while else statement
Python: Prepare a serializer for the class instance:
[Updating] Python Syntax cheat sheet for Java shop
How to write a ShellScript Bash for statement
[Introduction to Udemy Python3 + Application] 43. for else statement
Commands for creating a python3 environment with virtualenv
Procedure for creating a Python quarantine environment (venv environment)
A memo for creating a python environment by a beginner
Let's make a module for Python using SWIG
[Python] I want to use only index when looping a list with a for statement