Python3 Example (c)

Python decimal turn binary, octal, hexadecimal

The following code used to implement decimal turn binary, octal, hexadecimal:

Example (Python 3.0+)

-- coding: UTF-8 --

Filename : test.py

author by : www.runoob.com

Get user input decimal

dec = int (input ( "Enter number:"))

print ( "decimal number:", dec)
print ( "converted to binary is:", bin (dec))
print ( "octal as:", the OCT (dec))
print ( "converted to hexadecimal It is: ", hex (dec))
execute the above code output is:

python3 test.py
enter numbers: 5
Decimal number: 5
converted to binary is: 0b101
converted to octal: 0o5
converted to hexadecimal: 0x5

python3 test.py
enter numbers: 12
Decimal number: 12
converted to binary is: 0b1100
converted to octal: 0o14
converted to hexadecimal: 0xc
notes

Implementation

Decimal to binary:

DEC2BIN DEF (NUM):
L = []
IF NUM <0:
return '-' + DEC2BIN (ABS (NUM))
the while True:
NUM, REMAINDER = divmod (NUM, 2)
l.append (STR (REMAINDER))
IF == 0 NUM:
return '' .join (L [:: -. 1])
decimal to octal:

DEC2OCT DEF (NUM):
L = []
IF NUM <0:
return '-' + DEC2OCT (ABS (NUM))
the while True:
NUM, REMAINDER = divmod (NUM,. 8)
l.append (STR (REMAINDER))
IF == 0 NUM:
return '' .join (L [:: -. 1])
decimal-to-hexadecimal:

Base = [STR (X) for X in Range (10)] + [CHR (X) for X in Range (the ord ( 'A'), the ord ( 'A') +. 6)] DEF DEC2HEX (NUM):
L = []
IF NUM <0:
return '-' + DEC2HEX (ABS (NUM))
the while True:
NUM, REM = divmod (NUM, 16)
l.append (Base [REM])
IF NUM == 0:
return ' '.join (L [:: -. 1])
the Python code and the ASCII character conversion

The following code is used to implement the ASCII character conversion:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

Users input characters

c = input ( "Enter a character:")

User input ASCII code, and enter the numbers into integer

a = int (input ( "Please enter an ASCII code:"))

print (c + "is the ASCII code", the ord (C))
Print (A, "corresponding to character", chr (a))
to perform the above code is output is:

python3 test.py
enter a character: a
Enter an ASCII code: 101
A 97 ASCII code
101 corresponds to a character E
the Python greatest common divisor algorithm

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

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

The definition of a function

HCF DEF (X, Y):
"" "This function returns the greatest common divisor of two numbers of" ""

Get the minimum

if x > y:
smaller = y
else:
smaller = x

for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i

return hcf

Users enter two numbers

num1 = int (input ( "Enter first number:"))
num2 = int (INPUT ( "Enter the second number:"))

print (num1, "and", num2, "is the greatest common divisor", hcf (num1, num2) )
execute the above code output is:

Enter the first number: 54
enter the second number: 24
the greatest common divisor of 6 and 24 54
Notes

The following ideas can reduce cycle times:

  1. When the minimum value is the greatest common divisor, direct return;

  2. When the minimum value is not the greatest common divisor, the greatest common divisor is not greater than 1/2 of the minimum;

  3. Greatest common divisor should seek the greatest decrements descending cycle.

Example:

GCD DEF (A, b):
IF b> A:
A, b = b, A # b is the minimum value
IF A == 0% b:
return b # b is determined whether the greatest common divisor
for i in range (b / / 2 + 1, 1, -1): # reverse greatest common divisor more reasonable
IF B and 0% A% I == I == 0:
return I
return 0while (True):
A = int (INPUT ( "the Input 'A': "))
B = int (INPUT (" the Input 'B': "))
Print (GCD (A, B))
the Python least common multiple algorithm

The following code used to implement the least common multiple algorithms:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

Defined Functions

def lcm(x, y):

Get the maximum number of

if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

Get User Input

num1 = int (input ( "Enter first number:"))
num2 = int (INPUT ( "Enter the second number:"))

print (num1, "and", num2, "the least common multiple", lcm (num1, num2) )
execute the above code output is:

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

Follow these ideas can reduce cycle times:

1. When the maximum value is the least common multiple, returns the maximum value;

2. When the maximum value is not the least common multiple of the least common multiple is a multiple of the maximum value.

Example:

The least common multiple def lcm (a, b):

if b > a:
    a, b = b, a     # a为最大值
if a % b == 0:
    return a        # 判断a是否为最小公倍数
mul = 2             # 最小公倍数为最大值的倍数
while a*mul % b != 0:
    mul += 1
return a*mul

the while (True):
A = int (INPUT ( "the Input 'A':"))
B = int (INPUT ( "the Input 'B':"))
Print (LCM (A, B))
the Python achieve simple calculator

The following code is used to implement simple calculator, including the number of basic arithmetic two transport:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

Defined Functions

def add(x, y):
"""相加"""

return x + y
def subtract(x, y):
"""相减"""

return x - y
def multiply(x, y):
"""相乘"""

return x * y
def divide(x, y):
"""相除"""

return x / y

User input

print ( "Select operation:")
print ( ". 1, the sum")
print ( "2, subtract")
print ( ". 3, multiplied")
print ( ". 4, the division")

choice = input ( "Enter your choice (1/2/3/4):")

num1 = int (input ( "Enter first number:"))
num2 = int (INPUT ( "Enter the second number:"))

Choice == IF '. 1':
Print (num1, "+", num2, "=", the Add (num1, num2))
elif Choice == '2':
Print (num1, "-", num2, "=" , Subtract (num1, num2))
elif Choice == '. 3':
Print (num1, "*", num2, "=", Multiply (num1, num2))
elif Choice == '. 4':
Print (num1, " / ", num2," = ", Divide (num1, num2))
the else:
Print (" illegal input ")
to perform the above code is output is:

Select operation:
1, the addition
2 subtraction
3, multiplied by
4, divide
the input your choice (1/2/3/4): 2
enter the first digit: 5
enter the second number: 2
5 - = 3 2
Notes

Reference Method:

Divide DEF (X, Y):
# division
IF Y == 0:
Print ( '0 is not used as the denominator')
return
the else:
return X / Y

choice = int (input ( "Please select operation: \ n1, adding \ n2, subtraction \ n3, multiplied \ n4, division \ n Enter operation (are 1/2/3/4):"))
num1 = float (input ( "enter first number:"))
num2 = float (input ( "Please enter the second number:")) == IF Choice. 1:
Print ( "{} + {} = {} ".format (num1, num2, num1 num2 +)) == elif Choice 2:
Print (." {} - {} = {} "the format (num1, num2, num1-num2)) == Choice elif. 3:
Print (. "{X} = {{}}" the format (num1, num2, num1 num2 *)) == elif Choice. 4:
. Print ( "{} / {} = {}" the format (num1, num2, Divide ( num1, num2))) the else:
Print ( "illegal input selection operation")
the Python generated calendar

The following code is used to generate the specified date calendar:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

The introduction of the calendar module

importcalendar

Enter the specified date

yy = int (input ( "Enter the year:"))
mm = int (the INPUT ( "Enter the month:"))

Show calendar

print (calendar.month (yy, mm) )
to perform the above code is output is:

Enter the year: 2015
month entry:. 6
June 2015
of Mo Tu We Th Fr of Sa Su
. 1 2. 3. 4. 5. 6. 7
. 8. 9 10. 11 12 is 13 is 14
15 16. 17 18 is. 19 20 is 21 is
22 is 23 is 24 25 26 is 27 28
29 30
the Python recursive Fibonacci number

The following code uses a recursive manner to generate Fibonacci columns:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

recur_fibo DEF (n-):
"" "recursive function
output Fibonacci number" ""
IF n-<=. 1:
return n-
the else:
return (recur_fibo (. 1-n-) recur_fibo + (2-n-))

Get User Input

nterms = int (input ( "you want to output a few?"))

Check the digital input is correct

nterms IF <= 0:
Print ( "positive input")
the else:
Print ( "Fibonacci numbers columns:")
for I in Range (nterms):
Print (recur_fibo (I))
to perform the above code is output is:

You want to output a few 10?
That deed Fibonacci number column:
0
1
1
2
3
5
8
13
21
34
Python file IO

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

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

Write file

Open with ( "test.txt", "wt") AS out_file:
out_file.write ( "The text is written to the file \ n see me now!")

Read a file

Open with ( "test.txt", "RT") the in_file AS:
text = in_file.read ()
Print (text)
performed above code output is:

The text will be written to a file
see me now!
notes

w, mode r, wt, rt is inside the python file operations.

w is the write mode, r is the read mode.

t is the so-called windows platform-specific text mode (text mode), except that line breaks will automatically identify windows platform.

Unix-like platforms newline is \ n, and use the platform windows \ r \ n two ASCII characters for newline, uses internal python \ n to represent a newline character.

At rt mode, python when reading the text automatically \ r \ n is converted into \ n.

Under wt mode, Python be used for newline \ r \ n write file.

Python string Analyzing

The following code illustrates the determination Python string:

Examples

Filename : test.py

author by : www.runoob.com

A test case

print ( "a test case")
STR = "runoob.com"
Print (str.isalnum ()) # Analyzing all the characters are numbers or letters
print (str.isalpha ()) # Analyzing all the alphabetic characters are
print (str .isdigit ()) # judge all the characters are digital
print (str.islower ()) # judge all characters are lowercase
print (str.isupper ()) # judge all characters are uppercase
print (str.istitle ()) # judge all words are capitalized, like the title
print (str.isspace ()) # judge all the characters are blank character, \ t, \ n, \ r

print("------------------------")

Test Example Two

print ( "Test Example Two")
STR = "runoob"
Print (str.isalnum ())
Print (str.isalpha ())
Print (str.isdigit ())
Print (str.islower ())
Print (str.isupper ())
Print (str.istitle ())
Print (str.isspace ())
performs the above code is output is:

A test case
False
False
False
True
False
False
False

Test Example Two
True
True
False
True
False
False
the Python string case conversion

The following code demonstrates how to convert a string to uppercase letters, lowercase letters or a string such as:

Filename : test.py

author by : www.runoob.com

= str "www.runoob.com"
print (str.upper ()) # convert all characters to lowercase letters to uppercase letters
print (str.lower ()) # convert all uppercase characters to lowercase
print (str.capitalize ()) # is converted to the first letter of uppercase, lowercase remaining
print (str.title ()) # the first letter of each word is converted to uppercase, lowercase remaining
execution code output result of the above :

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

Well, I gave everyone here to share the end of the text to share a Bo Fuli

Python3 Example (c)
Python3 Example (c)

Access: group 839 383 765 plus python can get!

Guess you like

Origin blog.51cto.com/14186420/2405429