Python3 Example (1) | Novice Tutorial (19)

Table of contents

1. Example of Python Hello World

Two, Python number summation

(1) The following example is to enter two numbers through the user and calculate the sum of the two numbers:

(2) Two digital operations, summing we use the plus (+) operator, in addition, there are minus (-), multiplication (*), division (/), floor division (//) or Take the remainder (%).

(3) We can also combine the above operations into one line of code:

 3. Python square root

(1) The square root, also called the quadratic root, is expressed as 〔√ ̄〕.

(2) The following example is to input a number by the user and calculate the square root of this number:

(3) Negative and complex numbers can be used in the following ways:

4. Python quadratic equation

5. Python calculates the area of ​​a triangle

6. Python calculates the area of ​​a circle

Seven, Python random number generation

(1) In Python, you can use the built-in random module to generate random numbers.

 (2) random. random()

 (3) random.randint(a, b)

(四)random.choice(sequence)

(五)random.shuffle(sequence)

Eight, Python Celsius temperature to Fahrenheit temperature

Nine, Python swap variables

(1) The following example uses the user to input two variables and exchange them with each other:

(2) Do not use temporary variables

10. Python if statement

(1) The following example judges whether a number is positive, negative or zero by using the if...elif...else statement:

(2) We can also use the embedded if statement to achieve:

11. Python judges whether a string is a number

more ways

12. Python judges odd and even numbers

13. Python judges leap year

Fourteen, Python get the maximum value function

15. Python prime number judgment

16. Python outputs prime numbers within the specified range

Seventeen, Python factorial example

18. Python ninety-nine multiplication table

Nineteen, Python Fibonacci sequence

Twenty, Python Armstrong number

(1) The following code is used to detect whether the number entered by the user is an Armstrong number:

 (2) Obtain the Armstrong number within the specified period

21. Python decimal to binary, octal, hexadecimal

(1) The following code is used to convert decimal to binary, octal, and hexadecimal:

(2) Example of binary conversion

(3) Example of octal conversion

(4) Example of hexadecimal conversion

Twenty-two, Python ASCII code and character conversion

23. Python greatest common divisor algorithm

24. Python Least Common Multiple Algorithm

Twenty-five, Python simple calculator implementation

Twenty-six, Python generates a calendar

Twenty-seven, Python uses recursive Fibonacci sequence

28. Python file IO

29. Python string judgment

Thirty, Python string case conversion

31. Python calculates the number of days in each month

Thirty-two, Python gets yesterday's date

Thirty-three, Python list common operations

(1) list definition

(2) list negative index

(3) Adding elements to the list

(4) list search

(5) list delete elements

(6) list operator

(7) Use the join link list to become a string

(8) list split string

(9) Mapping analysis of list

(10) Analysis in dictionary

(11) list filter

Thirty-four, Python Joseph living dead game

Thirty-five, Python five fish

Thirty-six, Python realizes the stopwatch function

Thirty-seven, Python calculates the cubic sum of n natural numbers

Thirty-eight, Python calculates the sum of array elements

Thirty-nine, Python array flips the specified number of elements

(1) Define an integer array, and flip the specified number of elements to the end of the array.

(2) The following demonstrates placing the first two elements of the array behind the array.

 (3) Example 1

 (4) Example 2

 (5) Example 3


1. Example of Python Hello World

The following example is the first example of learning Python, that is, how to output "Hello World!":

 The output of executing the above code is:

Hello World!

Two, Python number summation

(1) The following example is to enter two numbers through the user and calculate the sum of the two numbers:

 The output of executing the above code is:

Enter the first number: 1.5
Enter the second number: 2.5
The numbers 1.5 and 2.5 add up to: 4.0

 In this example, we are summing two numbers entered by the user. The built-in function input() is used to get the user's input, and input() returns a string, so we need to use the float() method to convert the string to a number.

(2) Two digital operations, summing we use the plus (+) operator, in addition, there are minus (-), multiplication (*), division (/), floor division (//) or Take the remainder (%).

(3) We can also combine the above operations into one line of code:

 The output of executing the above code is:

$ python test.py 
Enter the first number: 1.5
Enter the second number: 2.5
The sum of two numbers is 4.0

 3. Python square root

(1) The square root, also called the quadratic root, is expressed as 〔√ ̄〕.

Such as: Mathematics language is: √ ̄16=4. The language description is: 16=4 under the root sign.

(2) The following example is to input a number by the user and calculate the square root of this number:

 The output of executing the above code is:

$ python test.py
Please enter a number: 4
 The square root of 4.000 is 2.000

In this example, we take the user to enter a number and use the exponent operator ** to calculate the square root of that number.

The program only works with positive numbers.

(3) Negative and complex numbers can be used in the following ways:

 The output of executing the above code is:

$ python test.py
Please enter a number: -8
The square root of -8 is 0.000+2.828j

 In this example, we use the sqrt() method of the cmath (complex math) module.

4. Python quadratic equation

The following example is to enter a number by the user and calculate the quadratic equation:

 The output of executing the above code is:

$ python test.py
Enter a: 1
Enter b: 5
Enter c: 6
The result is (-3+0j) and (-2+0j)

 In this example, we use the sqrt() method of the cmath (complex math) module to calculate the square root.

5. Python calculates the area of ​​a triangle

The following example is to calculate the area of ​​the triangle by inputting the length of the three sides of the triangle by the user:

 The output of executing the above code is:

$ python test.py
Enter the length of the first side of the triangle: 5
Enter the length of the second side of the triangle: 6
Enter the length of the third side of the triangle: 7
The area of ​​the triangle is 14.70

6. Python calculates the area of ​​a circle

The formula for the area of ​​a circle is:

In the formula r is the radius of the circle.

 

 The output of the above example is:

The area of ​​the circle is 78.550000

Seven, Python random number generation

(1) In Python, you can use the built-in random module to generate random numbers.

import random

 (2) random. random()

random.random() returns a random decimal between 0.0 and 1.0

 The output of executing the above code is:

0.7597072251250637

 (3) random.randint(a, b)

random.randint(a, b) returns an integer between a and b (inclusive).

random.randint(a,b)

 The function returns a number N, N is a number between a and b (a <= N <= b), including a and b.

The following example demonstrates how to generate a random number between 0 and 9:

 The output of executing the above code is:

4

(四)random.choice(sequence)

random.choice(sequence) is used to randomly select an element from a sequence:

 The output of executing the above code is:

4

(五)random.shuffle(sequence)

random.shuffle(sequence) is used to randomly sort the elements in the sequence:

 The output of executing the above code is:

[3, 2, 4, 5, 1]

Eight, Python Celsius temperature to Fahrenheit temperature

The following example demonstrates how to convert Celsius to Fahrenheit:

 The output of executing the above code is:

Enter temperature in Celsius: 38
38.0 Celsius to Fahrenheit is 100.4

 In the above example, the formula for converting Celsius to Fahrenheit is celsius * 1.8 = fahrenheit - 32. So get the following formula:

centigrade = (Fahrenheit - 32) / 1.8

Nine, Python swap variables

(1) The following example uses the user to input two variables and exchange them with each other:

 The output of executing the above code is:

Enter x value: 2
Enter y value: 3
The value of x after swapping is: 3
The value of y after swapping is: 2

In the above example, we created a temporary variable temp, and stored the value of x in the variable temp, then assigned the value of y to x, and finally assigned temp to the y variable.

(2) Do not use temporary variables

We can also swap variables in a very elegant way without creating temporary variables:

x,y = y,x

 So the above example can be modified to:

 The output of executing the above code is:

Enter x value: 1
Enter y value: 2
The value of x after swapping is: 2
The value of y after swapping is: 1

10. Python if statement

(1) The following example judges whether a number is positive, negative or zero by using the if...elif...else statement:

 The output of executing the above code is:

Enter a number: 3
A positive number

(2) We can also use the embedded if statement to achieve:

 The output of executing the above code is:

Enter a number: 0
zero

11. Python judges whether a string is a number

The following example determines whether a string is a number by creating a custom function is_number() method:

 We can also do this with an inline if statement:

The output of executing the above code is:

False
True
True
True
True
True
True
True
False

more ways

The Python isdigit() method detects whether a string consists of digits only.

The Python isnumeric() method checks whether a string consists of numbers only. This method is only for unicode objects.

12. Python judges odd and even numbers

The following example is used to determine whether a number is odd or even:

We can also do this with an inline if statement:

The output of executing the above code is:

Enter a number: 3
3 is odd

13. Python judges leap year

The following example is used to determine whether the year entered by the user is a leap year:

We can also do this with an inline if statement:

The output of executing the above code is:

Enter a year: 2000
2000 is a leap year
Enter a year: 2011
2011 is not a leap year

Fourteen, Python get the maximum value function

In the following example we use the max() method to find the maximum value:

 The output of executing the above code is:

2
b
2
2
80, 100, 1000 Maximum: 1000
-20, 100, 400 The maximum value is: 400
-80, -20, -10 The maximum value is: -10
0, 100, -400 Maximum value: 100

15. Python prime number judgment

A natural number greater than 1, except 1 and itself, cannot be divided by other natural numbers (prime numbers) (2, 3, 5, 7, etc.), in other words, the number has no other factors except 1 and itself .

 The output of executing the above code is:

$ python3 test.py 
Please enter a number: 1
1 is not prime
$ python3 test.py 
Please enter a number: 4
4 is not prime
2 times 2 is 4
$ python3 test.py 
Please enter a number: 5
5 is a prime number

16. Python outputs prime numbers within the specified range

Prime numbers (prime numbers), also known as prime numbers, are infinite. Not divisible by any divisor other than 1 and itself.

The following example can output prime numbers within the specified range:

 Execute the above program, the output is:

$ python3 test.py 
Enter interval min: 1
Enter range max: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Seventeen, Python factorial example

The factorial of an integer (English: factorial) is the product of all positive integers less than or equal to the number, and the factorial of 0 is 1. Namely: n!=1×2×3×...×n.

 The output of executing the above code is:

Please enter a number: 3
The factorial of 3 is 6

18. Python ninety-nine multiplication table

The following example demonstrates how to implement a nine-nine multiplication table:

 The output of executing the above code is:

 By specifying the value of the end parameter, you can cancel the output of the carriage return character at the end, so as not to wrap the line.

Nineteen, Python Fibonacci sequence

The Fibonacci sequence refers to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13, especially pointing out that: the 0th item is 0, and the 1st item is the first 1. Starting with the third term, each term is equal to the sum of the previous two.

The code to implement the Fibonacci sequence in Python is as follows:

 The output of executing the above code is:

How many items do you need? 10
Fibonacci sequence:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,

Twenty, Python Armstrong number

If an n -digit positive integer is equal to the sum of the nth powers of its digits , the number is called an Armstrong number.

For example 1^3 + 5^3 + 3^3 = 153.

Armstrong numbers up to 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

(1) The following code is used to detect whether the number entered by the user is an Armstrong number:

 The output of executing the above code is:

$ python3 test.py
Please enter a number: 345
345 is not an Armstrong number

$ python3 test.py
Please enter a number: 153
153 is the Armstrong number

$ python3 test.py 
Please enter a number: 1634
1634 is the Armstrong number

 (2) Obtain the Armstrong number within the specified period

 The output of executing the above code is:

Min: 1
Maximum value: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

 In the above example we output the Armstrong numbers between 1 and 10000.

21. Python decimal to binary, octal, hexadecimal

(1) The following code is used to convert decimal to binary, octal, and hexadecimal:

 The output of executing the above code is:

python3 test.py 
Enter number: 5
The decimal number is: 5
Converted to binary as: 0b101
Converted to octal is: 0o5
Converted to hexadecimal: 0x5

(2) Example of binary conversion

 Output result:

Binary number: 101010
Convert to decimal: 42
Convert to octal: 0o52
Convert to hex: 0x2a

(3) Example of octal conversion

 Output result:

Octal number: 52
Convert to decimal: 42
Converted to binary: 0b101010
Convert to hex: 0x2a

(4) Example of hexadecimal conversion

 Output result:

Hexadecimal number: 2a
Convert to decimal: 42
Converted to binary: 0b101010
Convert to octal: 0o52

Twenty-two, Python ASCII code and character conversion

The following codes are used to convert between ASCII codes and characters:

 The output of executing the above code is:

python3 test.py
Please enter a character: a
Please enter an ASCII code: 101
The ASCII code of a is 97
101 corresponds to the character e

23. Python greatest common divisor algorithm

The following code is used to implement the greatest common divisor algorithm:

 The output of executing the above code is:

Enter the first number: 54
Enter the second number: 24
The greatest common divisor of 54 and 24 is 6

24. Python Least Common Multiple Algorithm

The following code is used to implement the least common multiple algorithm:

 The output of executing the above code is:

Enter the first number: 54
Enter the second number: 24
The least common multiple of 54 and 24 is 216

Twenty-five, Python simple calculator implementation

The following code is used to implement a simple calculator, including basic addition, subtraction, multiplication and division of two numbers:

 The output of executing the above code is:

Select operation:
1. Add
2. Subtraction
3. Multiply
4. Divide
Enter your choice (1/2/3/4): 2
Enter the first number: 5
Enter the second number: 2
5 - 2 = 3

Twenty-six, Python generates a calendar

The following code is used to generate a calendar for a specified date:

 The output of executing the above code is:

Enter year: 2015
Enter month: 6
     June 2015
Mon Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

Twenty-seven, Python uses recursive Fibonacci sequence

The following code uses recursion to generate the Fibonacci sequence:

 The output of executing the above code is:

How many items do you want to output? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

28. Python file IO

The following code demonstrates Python's basic file operations, including open, read, and write:

 The output of executing the above code is:

This text will be written to the file
See me now!

29. Python string judgment

The following code demonstrates the judgment of Python strings:

 The output of executing the above code is:

Test case one
False
False
False
True
False
False
False
------------------------
Test case two
True
True
False
True
False
False

Thirty, Python string case conversion

The following code demonstrates how to convert a string to uppercase, or convert a string to lowercase, etc.:

# Filename : test.py
# author by : www.runoob.com

str = "www.runoob.com"
print(str.upper()) # Convert lowercase letters in all characters to uppercase letters
print(str.lower()) # Convert uppercase letters in all characters to lowercase letters
print(str.capitalize()) # Convert the first letter to uppercase and the rest to lowercase
print(str.title()) # Convert the first letter of each word to uppercase, and the rest to lowercase

The output of executing the above code is:

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

31. Python calculates the number of days in each month

The following code calculates the number of days in a month by importing the calendar module:

 The output of executing the above code is:

(3, 30)

The output is a tuple, the first element is the day of the week (0-6) corresponding to the first day of the month being checked, and the second element is the number of days in the month. The output of the above example means that the first day of September 2016 is Thursday, and there are 30 days in total in this month.

Thirty-two, Python gets yesterday's date

The following code gets yesterday's date by importing the datetime module:

 The output of executing the above code is:

2023-07-01

The above example output means that yesterday's date is July 1, 2023.

Thirty-three, Python list common operations

(1) list definition

>>> li = ["a", "b", "mpilgrim", "z", "example"]
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1]        
'b'

(2) list negative index

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1]
'example'
>>> li[-3]
'mpilgrim'
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]  
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'z']
>>> li[0:3]  
['a', 'b', 'mpilgrim']

(3) Adding elements to the list

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

(4) list search

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
>>> li.index("new")
2
>>> li.index("c")
Traceback (innermost last):
 File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li
False

(5) list delete elements

list.remove(x): x not in list >>> li.pop() # pop will do two things: remove the last element of the list, and then return the value of the removed element. 'elements' >>> li ['a', 'b', 'mpilgrim', 'example', 'new', 'two']














(6) list operator

>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new']
>>> li
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']        
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3
>>> li
[1, 2, 1, 2, 1, 2]

(7) Use the join link list to become a string

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> ["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
'server=mpilgrim;uid=sa;database=master;pwd=secret'

join can only be used on lists whose elements are strings; it does not perform any type coercion. Concatenating a list with one or more non-string elements will raise an exception. 

(8) list split string

>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s = ";".join(li)
>>> s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
>>> s.split(";")  
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s.split(";", 1)
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

split is the opposite of join, it splits a string into a multi-element list.

Note that the separator (";") is completely removed, it does not appear in any elements of the returned list.

split accepts an optional second argument which is the number of times to split.

(9) Mapping analysis of list

>>> li = [1, 9, 8, 4]
>>> [elem*2 for elem in li]   
[2, 18, 16, 8]
>>> li
[1, 9, 8, 4]
>>> li = [elem*2 for elem in li]
>>> li
[2, 18, 16, 8]

(10) Analysis in dictionary

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> params.keys()
dict_keys(['server', 'database', 'uid', 'pwd'])
>>> params.values()
dict_values(['mpilgrim', 'master', 'sa', 'secret'])
>>> params.items()
dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
>>> [k for k, v in params.items()]
['server', 'database', 'uid', 'pwd']
>>> [v for k, v in params.items()]
['mpilgrim', 'master', 'sa', 'secret']
>>> ["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']

(11) list filter

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
>>> [elem for elem in li if len(elem) > 1]
['mpilgrim', 'foo']
>>> [elem for elem in li if elem != "b"]
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
>>> [elem for elem in li if li.count(elem) == 1]
['a', 'mpilgrim', 'foo', 'c']

Thirty-four, Python Joseph living dead game

30 people on a boat, overloaded, need 15 people to disembark.

So people line up in a line, and the position in line is their number.

Counting starts from 1 and people who count to 9 disembark.

This cycle continues until there are only 15 people left on the boat. Which numbered people have disembarked?

 Execute the above example, the output result is:

No. 9 disembarked
disembarked on the 18th
disembarked on the 27th
No. 6 disembarked
disembarked on the 16th
disembarked on the 26th
No. 7 disembarked
disembarked on the 19th
Disembarked on the 30th
Disembarked on the 12th
disembarked on the 24th
No. 8 disembarked
disembarked on the 22nd
No. 5 disembarked
disembarked on the 23rd

Thirty-five, Python five fish

Five people A, B, C, D, and E went fishing together one night, and they were all exhausted in the early morning of the next day, so they each found a place to sleep.

There are three shots in the day, A wakes up first, he divides the fish into five parts, throws away the extra fish, and takes his own part.

B wakes up the second time, also divides the fish into five parts, throws away the extra fish and takes his own part. .

C, D, and E wake up in turn and take the fish in the same way.

How many fish did they catch at least?

 operation result:

There are 3121 fish in total

Thirty-six, Python realizes the stopwatch function

The following example uses the time module to implement the stopwatch function:

 The test results are:

Press Enter to start timing, and Ctrl + C to stop timing.

start
Timing: 3.0 seconds
Timing: 5.0 seconds
^C end 6.0 seconds
Total time: 6.69 secs

Thirty-seven, Python calculates the cubic sum of n natural numbers

Calculation formula 13 + 23 + 33 + 43 + .... + n3

Implementation requirements:

Input: n = 5

output: 225

Formula: 13 + 23 + 33 + 43 + 53 = 225

Input: n = 7

Input: 784

Formula: 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784

 The output of the above example is:

225

Thirty-eight, Python calculates the sum of array elements

Define an array of integers and calculate the sum of the elements.

Implementation requirements:

Input: arr[] = {1, 2, 3}

output: 6

Calculation: 1 + 2 + 3 = 6

 The output of the above example is:

The sum of the array elements is 34

Thirty-nine, Python array flips the specified number of elements

(1) Define an integer array, and flip the specified number of elements to the end of the array.

For example: (ar[], d, n) flips the first d elements of the array arr with length n to the end of the array.

(2) The following demonstrates placing the first two elements of the array behind the array.

Raw array:

 After flipping:

 (3) Example 1

 The output of the above example is:

3 4 5 6 7 1 2

 (4) Example 2

 The output of the above example is:

3 4 5 6 7 1 2

 (5) Example 3

 The output of the above example is:

3 4 5 6 7 1 2

Guess you like

Origin blog.csdn.net/wuds_158/article/details/131495981