5 hours getting started with python - input and output and formatted output

5 hours getting started with python (1) - variables and input and output

output function

Of course, the beginning of learning a language is to output hello world, without the beginning of outputting hello world, there is no soul. So how to use python to output hello world? Let's take a look at the code.

print("hello world")

Then this code is written, python is a typical minimalism. Isn't it easy.

variable

In python, variables are not as strict as in C language. We often use int and float, and when defining variables, there is no need to declare the data type. Suppose we want to define a string variable, then we only need to declare it like this.

a = "hello world"
print(a)
b = 10
print(b)
c = 10.01
print(c)

So how can we know what type a variable is? Then we use our type() function.

a = "hello world"
print(type(a))
print(a)
b = 10
print(type(b))
print(b)
c = 10.01
print(type(c))
print(c)

We can see that

<class 'str'>
hello world
<class 'int'>
10
<class 'float'>
10.01

Among them, str is string, which is a string type, int is an integer type, and float is a floating-point number type.

input function

Now let's learn about the input function. The type accepted by the input function is a string type by default. But it can be converted by functions such as int() or float(). code show as below.

my_num = input("请输入您的数字")
print(type(my_num))
print(my_num)
my_num = int(my_num)
print(type(my_num))
print(my_num)

The above code requires us to input our own number, and then output it. We can see that my_num is a string type, but after we modify it through int(), our number variable has an int type.

Methods to format output

There are many ways to format, we will explain a format method. First of all, formatting input is generally an operation on strings. Some variables can be inserted into our strings. In fact, it is similar to %d or %f in printf in our C language or C++. Let's take a look at the code.

a = "hello world, '{}'".format("loading_create")
print(a)

The result of running is

hello world, 'loading_create'

Guess you like

Origin blog.csdn.net/weixin_50153843/article/details/125746887
Recommended