Summary of 13 instances in Python 3

Posted by yousaf931 on Wed, 06 Nov 2019 15:30:21 +0100

1. Python number summation

# -*- codingLuft-8 -*-
#Filename: test.py
#author by:Leq

#User input number
num1 = input("Enter the first number:")
num2 = input("Enter the second number:")
#Summation
sum= float(num1)+float(num2)   #To do an operation, you must ensure that the character format is converted to the integer init or floating-point float before the operation

#First display mode: format output
print("The result of adding two numbers is:%d"%sum)
#Second display mode:. format()
print('number {0} and {1} The results are as follows: {2}'.format(num1, num2, sum))

2. Square root √ ~

# -*- codingLuft-8 -*-
#Filename: square root.py
num = float(input('Please enter a number: '))
num_sqrt = num ** 0.5
print(' %0.3f The square root of is %0.3f'%(num ,num_sqrt))#Floating point number 3 places after decimal point

3. Calculate triangle area; note: triangle area = (half perimeter * (half perimeter side length A) * (half perimeter side length B) * (half perimeter side length C)) xx 0.5

# -*- codingLuft-8 -*-
#Filename: calculate triangle area.py
#Operation process: triangle area = (half perimeter * (half perimeter side length A) * (half perimeter side length B) * (half perimeter side length C)) * * 0.5
a = float(input('Input the first side length of triangle: '))
b = float(input('Enter the second side length of the triangle: '))
c = float(input('Enter the third side length of the triangle: '))
 
#Calculate half perimeter
s = (a+b+c)/2

#Calculated area
area = (s*(s-a)*(s-b)*(s-c))**0.5
print('The area of a triangle is%0.2f'%area)

4. Generate random number

# -*- codingLuft-8 -*-
#Filename: generate random number.py
#Introducing random module
import random
print(random.randint(0,9))

5. Judge odd and even numbers

# -*- codingLuft-8 -*-
#Filename: judge odd even. py
num = int(input("Please enter a number to judge odd even number:"))
if num%2 ==0:
    print('%d Even numbers'%num)
else:
    print('%d Not even numbers'%num)

6. Determine leap year

# -*- codingLuft-8 -*-
#Filename: determine leap year.py
#A leap year is a year in which the whole century can be divided by 400 and the non whole century can be divided by 4

num = int(input("Please enter a year to determine if it is a leap year:"))
if num%100 == 0:
    if num%400 == 0:
        print("%s Year is a leap year."%num)
    else:
        print("%s Year is not a leap year"%num)
else:
    if num%4 == 0:
        print("%s Year is a leap year."%num)
    else:
        print("%s Year is not a leap year"%num)

7. Judge whether it is a prime number

# -*- codingLuft-8 -*-
#Filename: Prime judgment.py
#Prime number: 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.

num= int(input("Input a number, and the system can judge whether it is a prime number or not:"))
if num >1:
    for i in range(2,num):
        if num%i==0:
            print('%s Not prime numbers.'%num)
            break
    else:
        print('%s Prime number'%num)
else:
    print("Please enter a number greater than 1")

8, factorial

# -*- codingLuft-8 -*-
#Filename: factorial instance.py
#Factorial: natural number, all multiplication

num =int(input("Enter a number to calculate the factorial:"))

f=1
if num <0:
    print("SORRY,Negative numbers have no factorials")
if num==0:
    print("0 The factorial of is 1")
else:
    for i in range(1,num+1):
        f=f*i
 #       f+=1
print("%s The factorial is%s"%(num,f))

9. Multiplication table

# -*- codingLuft-8 -*-
#Filename: multiplication table.py
#Two for loops, print() with newline

for i in range(1,10):
    for j in range(1,i+1):
        print('%s*%s=%s'%(i,j,i*j),end=' ')  #The print() function has its own line feed '\ h\t', which is removed here. Let the output finish this section before line feed
    print()   #print()  == print('\n\t')

10. Judge whether it is a number [this access stock in]

# -*- coding: UTF-8 -*-
# Python learning exchange QQ group: 857662006  
# Filename : test.py
 
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False
 
# Test strings and numbers
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
 
# Test Unicode
# Arabic 5
print(is_number('٥'))  # True
# Thai 2
print(is_number('๒'))  # True
# Chinese numerals
print(is_number('Four')) # True
# Copyright number
print(is_number('©'))  # False

11. Python decimal to binary (bin), octal (oct), hex (HEX)

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

print("Decimal numbers are:", dec)
print("Convert to binary as:", bin(dec))
print("Convert to octal:", oct(dec))
print("Convert to hex as:", hex(dec))

12. Maximum common divisor

# Filename : test.py
 
# Define a function
def hcf(x, y):
   """This function returns the greatest common divisor of two numbers"""
 
   # Get 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
 
 
# User enters two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter the second number: "))
 
print( num1,"and", num2,"The maximum common divisor of is", hcf(num1, num2))

13. Generate calendar [rookie tutorial runoob.com]

# Filename : test.py

# Introduction of calendar module
import calendar

# Enter the specified month and year
yy = int(input("Year of importation: "))
mm = int(input("Input month: "))

# Display calendar
print(calendar.month(yy,mm))  #Notice the format here

Topics: Python