PR

Mastering Python Basic Syntax: A Step-by-Step for Beginners with Examples

python
記事内に広告が含まれています / This article contains ads
About this article

You will learn the basic syntax necessary for Python programming.

numeric

Numerical operations and operators

First, let's use Python to perform numerical operations.

We will use Jupyter Notebook.

Let's demonstrate the process of various numerical operations. At first, executes the following example.

5 + 2

Then, you get following value.

7

note: Without spaces, like 5+2, you can execute the code correctly but it makes the code easier to read with spaces before and after "+".

Python allows a variety of numerical operations, including the four basic arithmetic operations (add, subtract, multiple, divide). Let's try to execute the following calculations and check the results.

Even if you get strange results, do not panic (or refer to the explanation article further down).

3 + 2

8 - 4

8 * 4

42 / 6

21 / 8

21 // 8

21 % 8

2 * 5

2 ** 5

4 * 2.5

3 * 4.2

0.1 + 0.1 + 0.1

These are the basic four arithmetic operations. The symbols used in calculations are called "operators".

The "+" and "-" operators for addition and subtraction and "*" and "/" operators for multiplication and division.

Among the examples above;

42 / 6

Output: 7.0

Note that the result of the 42 / 6 run is 7.0, not 7.
In Python, for integer-to-integer division, the result of the operation is a real number, even if the answer is divisible.

As another division operators, "//" is an operator to round down to the nearest whole number while "%" is an operator that calculates the remainder of the division.

21 / 8

Output: 2.625

21 // 8

Output: 2

21 % 8

Output: 5

The operator "*" with one asterisk is a simple multiplication, while the operator "**" with two asterisks means squared; that is, 2 ** 5 means 25. Then the result of the calculation is 32.

2 * 5

Output: 10

2 ** 5

Output: 32

Finally, in some calculations of real numbers, the answer may not be exactly what you think of.

3 * 4.6

Output: 13.799999999999999

Originally it should be 3 × 4.6 = 13.8, but python caluculate 13.79999999….

0.1 + 0.1 + 0.1

Output: 0.30000000000000004

This one is also 0.30000000000000004, not 0.3, which is a strange result.

This is due to the computer's internal calculation mechanism of "converting to binary numbers," which inevitably results in approximate values. Care must be taken when seeking accuracy in arithmetic operations involving real numbers.

Numerical operator summary

Types of operatorsDescription of operation
+addition
-subtraction
*multiplication
/division
//division and round down to the nearest whole number
%finding the remainder of a division
**power

integer

0, natural numbers (1, 2, …), and negative integers (-1, -2, …) can be handled as integer.
If there is a decimal point, it will be a real number.

In addition, Python also supports binary formats, octal formats, and hexadecimal formats.

formatprefixfunction to covert
binary0bbin()
octal0o
(The first letter of 0o is zero, the second letter is a lowercase o)
oct()
hexadecimal0xhex()

Let's enter the following in Jupyter Notebook. Each will be converted to a number.

0b101

Output: 5

0o101

Output: 65

0x101

Output: 257

Conversely, to convert from decimal to binary/octal/hexadecimal formats, execute the bin(), oct(), and hex() functions. Write the integer in the parentheses of each function.

Let's execute the following with Jupyter Notebook.

Note that the result of executing these functions is not the number itself, but a string.

bin(5)

Output: '0b101'

oct(65)

Output: '0o101'

hex(257)

Output: '0x101'

Real numbers (floating point numbers).

Numbers with decimal point are called real numbers (float numbers); Python's internal processing uses floating point numbers.

If you want to handle a decimal point with a large number of digits, you can use exponential notation (m × er).

Check the following in Jupyter Notebook.

5.224e+6

Output: 5224000.0

We use the letter e, which means the same as 10. In other words, 5.224e+6 calculates 5.224 × 106.

Complex numbers.

A complex number consists of a real part and an imaginary part. You can create a complex number in Python using the complex() function or by directly writing it with the j suffix to denote the imaginary part. Example using the complex() function:

# 3 is the real part, and 4 is the imaginary part
complex_num1 = complex(3, 4)
print(complex_num1)

Output: (3+4j)

Example using direct notation:

# 2 is the real part, and 5 is the imaginary part
complex_num2 = 2 + 5j  
print(complex_num2)

Output: (2+5j)

Examples above represent complex numbers, where the real part is 3 and 2 respectively, and the imaginary part is 4 and 5 respectively. Because complex numbers are special numbers, they will be surrounded by parentheses.

This is not a study of mathematics, so we will not go into details.

Conversion of integer/number/complex number

The conversion from integer to real number and from integer/real number to complex number can be very simple, just use the following functions.

Numeric TypeFunction to convert
integerint()
real numberfloat()
complex numbercomplex()

Check it out the following in Jupyter Notebook.

int(123.45)

Output: 123

float(567)

Output: 567.0

complex(89)

Output: (89+0j)

String

You may notice that many programming textbook use the sentence, "Hello, world!" at the begining. In Python, data like "Hello, world!" is handled as a string.

Note that when working with strings, remember to wrap the string in single or double quotation marks like below.

print("Hello, world!")

Output: Hello, world!

Note that in Python, there is no clear difference between strings enclosed in single quotation marks(') and strings enclosed in double quotation marks(").

Display quotation marks as strings

However, care must be taken if you wish to display single or double quotation marks as strings. An example is shown below.

print("Hello, "Python" world!")

This code cause an error!

Because the error is caused by the incorrect use of double quotations within the string. The error comes from having double quotations inside a double-quoted string. This confuses the Python interpreter because it first interprets the string starting with "Hello, " then it encounters another strings with "Python," and it doesn't understand how to continue.

If you want to display quotation marks as strings, you can do either of the followings.

Enclose in separate quotation marks

If you want double quotation marks to appear as a string, enclose entire strins with single quotation marks. Conversely, if you want single quotation marks to appear as a string, enclose them in double quotation marks. By using single quotations inside the double-quoted string or vice versa, you avoid confusing the Python interpreter.

print('Hello, "world"')

Output: Hello, "world"

print("Hello, 'world'")

Output: Hello, 'world'

Use escape sequences.

When you add a backslash before quotation marks in your code, it's called an escape sequence. An escape sequence is like a special code that tells Python to treat the following character in a special way. In this case, the backslash before the quotation marks is a signal to Python that it should not interpret those quotation marks as the end of a string.

For example, in Windows, if you want to include quotation marks within a string, you can use the escape sequence: \. So, instead of causing confusion in your code, Python understands that the quotation marks inside the string are part of the text and not the end of the string itself. This helps you include certain characters without disrupting the syntax of your code.

print("Hello, \"Python\" world!")
Hello, "Python" world!

Display strings with line breaks.

To display a line break in the middle of a string, you must use following techniques.

Use escape sequences

 \n is treated as a new line.

print("Hello,\nworld!")

Hello,
world!

Use Heard Documents.

When you put your text between three pairs of quotation marks (""" … """), you don't have to worry about using special symbols for line breaks in Python. It's a simpler way to include multiple lines of text without dealing with additional formatting.

print("""
Hello,

world!
""")

Hello,

world!

String concatenation and repetition.

In numeric, + was the addition operator.

123 + 456

Output: 579

However, using + in a string results in concatenation of strings.

"123" + "456"

Output: '123456'

"456" + "123"

Output: '456123'

The string "123" and "456" are concatenated to form the string "123456". And also the string "456" and "123" are concatenated to form the string "456123".

Be careful, the 123 (number) and the string "123" are not the same thing.

Likewise, writing with the * operator, like multiplication, repeats the string.

"123" * 3

Output: '123123123'

Conversion between numeric and string

Again, the number 123 is not the same as the string "123". However, there are some operations that are easier to perform by treating a number as a string.

Convert a number to a string.

To convert a number to a string, use the str() function. Inside the parentheses of str() is the number you want to convert into a string.

number = 42
string_to_number = str(number)
type(string_to_number)

Output: str

In Python, the type() function is used to determine the data type of a given object or variable. It returns the type of the object, which can be one of the standard built-in types such as int, float, str, list, tuple, etc.

In the example above, type(string_to_number) returns the type of "string_to_number" variable, which is an string (str).

Convert strings to numbers.

Conversely, if you want to convert a string-formatted item back to a number, use int().

string_number = "42"
string_to_number = int(string_number)
type(string_to_number)

Output: int

In the example above, the strings "42" is converted to numbers using int().

Variables

Now we will look at variables.

What is a variable?

So far, you've been running programs that are just one line, but soon you'll write longer programs that go across many lines. When this happens, you'll often want to store the results of your actions and use them later. The storage spot for this data is called a "variable".

Try using variables.

Let's quickly check how variables are used in Python in Jupyter Notebook.

a = 5
b = 4

c = a + b

print(c)

Output: 9

Let's break it down, line by line.

a = 5

Here we have defined variable a.
We assign 2 into the variable a.

In mathematics, the symbol = denotes equality between the left and right sides. However, in Python, = is used to mean "assign the content on the right side to the left side." To assign data to a particular variable in Python, you can express it as "variable name = data."

Then

b = 4

We defined a variable called b and assigned the integer 4. Since this is also just an assignment process, no result is displayed.

c = a + b

a + b is the process of "adding the contents of variable a to the contents of variable b." Since c = a + b, the result of the addition of a + b is assigned to variable c.

Although the calculation process is performed, the results are not immediately displayed because the calculation results are assigned to variables.

print(c)

print() function displays the contents of c. And then you get 9.

If you want to print the contents of a variable, simply write print(variable name) like this. Variable names do not need to be enclosed in quotation marks. For example, if you enclose the variable c in quotation marks as shown below, it will be treated as string, "c".

print("c")

Output: c

The examples above are calculations between variables, but you can also add variables and numbers together as shown below.

d = 5
e = d + 3

print(e)

Output: 8

Cautions on using variables

When you're writing code in Python, you can give your variables any name you want. For example, using single letters like a, b, or c is okay and won't cause errors.

However, when you're writing more serious code, it's a good idea to use names that make it clear what the variable is for. For instance, if you have a variable storing an address, call it address. If it's for age, call it age.

If you need to use more than one word for a variable name, Python suggests connecting the words with underscores, like last_name or first_name. This is called snake case.

Be careful not to use reserved words like "if", "while" or "print" as variable names, as they have special meanings in Python. If you ever get an error in your code, double-check if you're using a reserved word.

You can find a list of reserved words in the official Python documentation.

Overwrite the same variable.

It is also possible to overwrite a variable that already contains data with new data.

a = 100

a = a + 100

print(a)

Output: 200

The above example first assigned 100 to the variable a. Next, the process "overwrites the contents of variable a (the integer 100) with the addition of 100 to a".

Therefore, the contents of variable a will eventually change to 200.

Discard variable

Once you create a variable in Jupyter Notebook, you can easily check what's stored in it (we call it a reference) as many times as you need until you leave the interactive environment. If you no longer need a variable and want to get rid of it, use the command del().

print(a)

Output: 200

del(a)

print(a)

error message!

As shown above, an attempt to refer a variable that is "undefined" or "destroyed by del()" will result in the error NameError: name 'variable name' is not defined.

Variable data types

When I say "data type" for a variable in Python, I'm just talking about "what kind of data it holds." You can still use print(variable name) to see the actual data, but if you only want to know the type of data (we call it type), there's a handy command called type().

a = 123
b = 123.456
c = "abcdefg"
d = 7 + 4j
type(a)

Output: int

type(b)

Output: float

type(c)

Output: str

type(d)

Output: complex

In the example above, we've set up the variable
- a to hold the whole number 123
- b for the decimal number 123.456,
- c for the word "abc"
- d for the complex number (7 + 4j)

When we use the type() function to check each of them, it tells us that
- a is an int (short for integer)
- b is a float (which means a real number with decimals)
- c is a str (short for string)
- d is a complex (indicating a complex number).

Overwrite a variable with data of another type.

While some programming languages lock a variable into a specific "data type" once you give it certain data, Python is more flexible.

You can change the type of data a variable holds by assigning it a different type.

a = 123
type(a)

Output: int

a = "abc"
type(a)

Output: str

In the example above, the variable a started by holding the number 123, but then we changed it to store the word "abc." If you use type(a) before and after this change, you'll notice a beautiful transformation.

Even though this might seem different from what you've seen in other languages, this flexibility is one of the special features of Python.

Operator

We have already discussed the + and * operators in the section on numbers and strings, and there are a wide variety of operators available for performing various operations in Python. We will summarize them here.

Numerical operator

We learned this at the numerical value, but let's review it.

Types of operatorsDescription of operation
+addition
-subtraction
*multiplication
/division
//division and round down to the nearest whole number
%finding the remainder of a division
**power

String operator

We have also learned in previous lessons that processing a string with + or * is different from adding or multiplying numbers. Here is a summary of the contents.

Types of operatorsDescription of operation
+string concatenation
*Repeat a string a specified number of times

Substitution operator

We have already learned the operator = used for variable assignment. Also, we have also learned that it is possible to overwrite the contents of a variable in previous lessons.

Python also provides another assignment operator, +=.

a = 1
a += 1
print(a)

Output: 2

In Python, when you see the statement a = a + 1 or a += 1, they both do the exact same thing—they increase the value stored in the variable a by 1.

Let's look into the details:

a = a + 1: This is a common way to increment the value of a. It takes the current value of a, adds 1 to it, and then assigns the result back to a.
For example, if a was 5, after this operation, it would become 6.

a += 1: This is a shorter and more concise way of expressing the same thing. It's like a shortcut for a = a + 1. It means "add 1 to the current value of a and store the result back in a."
So, if a was 5 before, it becomes 6 after this operation.

The += operator isn't limited to just adding 1; you can use it for other numbers as well. For instance, a += 5 would add 5 to the current value of a.

These kinds of operators (+=, -=, *=, /=) are handy and are available for all sorts of mathematical operations. They make your code shorter and often easier to read.

Types of operatorsExamples of usageDescription of operation
+=a += ba plus b back into a
-=a -= ba minus b back into a
*=a *= ba multiplied by b back into a
/=a /= ba divided by b back into a
//=a //= bDivide the contents of a by b, and reassign the number rounded down to the nearest whole number to a
%=a %= bremainder of the content of a divided by b back into a
**=a **= bsquare of the contents of a back into a

Boolean and comparison operators

One of the Python data types is called boolean. This is a data type that can only be True or False.

Looks like a string but is not a string. It is written as True or False without enclosing quotation marks. This boolean value can be converted to a number by using int(), with True being 1 and False being 0.

int(True)

Output: 1

int(False)

Output: 0

In the following example, we are working with a variable called age. Let's go through it step by step:

Setting the Initial Value:

   age = 25

Here, we are initializing the variable age with a value of 25. So, initially, age is 25.

Comparing with the "Greater Than" Operator (>):

   age > 20

This line checks if the value stored in age is greater than 20. In this case, 25 is indeed greater than 20, so the condition is satisfied, and it is True.

Changing the Value of age:

   age = 18

Now, we change the value of age to 18. So, age is no longer 25; it's now 18.

Re-evaluating the Condition:

   age > 20

This line checks again if the value stored in age is greater than 20. However, now with the new value (18), the condition is not satisfied, and it is False.

Comparison Operators:
Operators like > (pronounced "greater than") are called comparison operators. They help us compare values and make decisions in our code. Here are some common ones:

This section summarizes the comparison operators provided in Python.

Types of operatorsExamples of usageContents
>a > bWhether the content of a is greater than the content of b
<a < bWhether the content of a is smaller than the content of b
>=a >= bWhether the content of a is greater than or equal to the content of b
<=a <= bWhether the contents of a are less than or equal to the contents of b
==a == bWhether the contents of a are equivalent to the contents of b
!=a != bWhether the contents of a are different from the contents of b

Logical operators

When you need to set multiple conditions, like checking if someone is "20 years old or older and 65 years old or younger," Python provides logical operators to help you combine conditions. There are three main logical operators:

Types of operatorsExamples of usageContents
andage >= 20 and age <= 65True only if all conditions are satisfied
orage >= 20 or age <= 65True if at least one of the conditions is satisfied
notnot(a >= 20)False if the specified expression is satisfied
True if not

and: This operator is used to combine two conditions, and both conditions must be True for the overall expression to be True. In the context of our example, using "and" allows you to check if someone meets both conditions—being "20 years or older" and "65 years or younger".

age = 30
result = age >= 20 and age <= 65
result

True

or: The "or" operator is used to combine two conditions, and the overall expression is True if at least one of the conditions is True. In our example, it allows you to check if someone is either "20 years or older" or "65 years or younger". Example:

age = 18
result = age >= 20 or age <= 65
result

True

not: The "not" operator is a unary operator that negates the result of a condition. If a condition is True, not makes it False, and vice versa. Example:

age = 25
result = not (age < 20)
result

True

These logical operators provide a powerful way to create complex conditions by combining simpler ones. They help you express intricate requirements in your code, allowing you to make decisions based on multiple factors.

In Python, you can use symbols to represent logical operations.
The symbol & can replace the word "and," and the symbol | can replace the word "or." However, there's a key point to note:

Logical Conjunction (&): The & symbol is used for logical conjunction, which means both conditions must be True for the overall expression to be True. For example, (age >= 20) & (age <= 65) checks if someone is both 20 years or older and 65 years or younger.

Logical Disjunction (|): The | symbol is used for logical disjunction, where the overall expression is True if at least one of the conditions is True. For instance, (age >= 20) | (age <= 65) checks if someone is either 20 years or older or 65 years or younger.

Now, the symbols & and | are also used in bitwise operations, but in the context of logical operations, they serve a different purpose. The words "and" and "or," which were introduced earlier, represent logical conjunction and logical disjunction of pooled operations. Pooled operations include comparison operators like > and ==.

It's crucial to note that the symbols & and | have higher precedence than pooled operations and comparison operators. This means they are processed first in an expression. To avoid unexpected behavior due to precedence, it's recommended to enclose the comparison operations in parentheses when using & and |.

For example:

result = (age >= 20) & (age <= 65)
# The parentheses ensure that the comparison operations are evaluated before the logical conjunction.

Understanding precedence is essential for writing accurate and predictable code. If you'd like more details on operator precedence, you can refer to the documentation or additional resources on the topic.

Comments

In programming, you often encounter situations where you want to add notes or explanations to your code. This is where comments come in handy. Comments are lines in your code that are not executed; instead, they serve as notes.

In Python, comments are created using the # symbol. Here's how you can use comments:

Single-Line Comments

You can add comments at the end of a line to explain what the code does.

a = 10 # Assign 10 to variable a
b = 20 # Assign 20 to variable b
print(a)
print(b)

10
20

In-line Comments

Comments can be added after the code on the same line to provide additional context.

# The following overwrites a
a = 50
print(a)

50

Multi-Line Comments:

For longer explanations, you can use triple-quotes (""") to create multi-line comments.

# Addition
c = a + b

"""
By describing it this way.
Multiple lines of comments can also be written.
Finally, the contents of c are displayed.
"""

print(c)

70

When you run this code, the comments are ignored by the Python interpreter. They are purely for human understanding.

Using comments is a good practice because it makes your code more readable and helps others (or even yourself) understand the purpose and functionality of different parts of the code. Remember, clear and well-documented code is easier to maintain and share with others.

Function

The word "function" is a word we learned in math, and it is safe to say that functions in Python have much the same meaning.

For example,

y = f(x)

We learned this form of function in mathematics: there is a formula defined by a variable called x, and when you assign some number to x and calculate it, you get one answer (y).

f(x) = 2x + 3

If f(x) is defined as above, then substituting 1 for x yields 5, and substituting 2 for x yields 7.

Python functions are much the same. You give some data to a function, it is processed, and some result is obtained.

In Python functions, the data given to a function is called argument and the result of the function's processing is called return value.

Some functions require one argument, some require two or more, and some require none.

For example, print() function in Python. When you use print(), you put the "data you want to show on the screen" inside the parentheses. If you want to display the words "Hello, world!", you would type print("Hello, world!").

print("Hello, world!")
Hello, world!

Python comes standard with a variety of built-in functions like; print(), sum(), and so on.

Data input

The print(), which displays strings to the screen, is the function we have already learned.

There's a handy function that lets your program get information from the user while it's running. This function is called input().

Now, when you use input(), you can put a message in the parentheses (that's what we call an argument) to ask the user for specific information. Whatever they type in response becomes the data your program gets back. Since input() gives you something back, you'd usually write it like this:

variable_name = input("Please type something:")

For example,

name = input("Enter your name:")

Enter your name:Tom

The string "Tom" entered from the keyboard is stored in the variable (name).

Then you can run the code like this.

print("Your name is " + name + "!")

Your name is Tom!

Notes on input().

When you use input(), it gives you back information, but here's the thing: no matter what you type, like a number, it treats it like a "string" of characters.

So, if you're expecting a number but you use it in a math formula, Python might get confused. It's like trying to use words in a math problem. You'll see an error message that looks something like this:

num = input("Enter any number:")

Enter any number:10

Then

num = num + 10

You will recieve TypeError!

If you see an error like "TypeError: must be str, not int," it means you're trying to add a number to something that's not a number. The issue is that the variable you're using (let's call it num) has information in it that's treated like words, not a number.

To fix this, you can use a trick. Wrap the input() function with int() function:

num = int(input("Enter a number:"))

This way, the value turned into a number, and you can use it in math without any problems. This is like telling Python, "Hey, treat whatever comes from input() as a number, not words."

So, when you see that error, just remember to use int() to turn your input value into a number, and you'll be good to go!

Other basic functions that can be used for numbers and strings

In addition to print() and input(), Python provides various standard functions such as int() and float() for numbers, and str() and len() for strings.

example code

Here's a Python code practice problem to generate username. This is a good exercise for practicing variable assignment, string manipulation, and user input handling in Python.

# Create a program to generate a username based on user input.
print("Welcome to the Username Generator")

# Ask the user for their favorite color.
color = input("What's your favorite color?\n")

# Ask the user for their birth year.
birth_year = input("What year were you born in?\n")

# Generate the username by combining the color and the birth year.
username = color + birth_year

# Display the generated username.
print("Your username could be: " + username)

In this problem, users are asked to input their favorite color and their birth year. Then, a username is generated by concatenating the color with the birth year.

Summary

In this lesson, you learned about the properties of numeric and string data, as well as the basic elements of writing Python programs: variables, operators, comments, and functions. All of these are necessary, so even if it is impossible to learn them all at once, it is advisable to learn them gradually by creating programs while constantly reviewing them.

コメント