[python] week1-3: Number type and operation

Python language program @ bulk heaven, yellow heaven feather, courtesy

1. Program introduction

1.1 Example 1 User import

n = input("Import N:")
sum = 0
for i in range(int(n)):
    sum += i + 1
print("1 to N summation result:",sum)

1.2 Example 2 Formalized export multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print("{}*{}={:2}".format(j,i,i*j),end=' ')
    print(' ')

1.3 Example 3 Introduction to graphicization

import turtle
import time
turtle.pensize(2)
turtle.bgcolor("black")
colors = ["red","yellow","purple","blue"]
turtle.tracer(False)
for x in range(400):
    turtle.forward(2*x)
    turtle.color(colors[x % 4])
    turtle.left(91)
turtle.tracer(True)

Export:

2. Example: Temperature conversion program

val = input("please input the temprature(eg:32C):")
if val[-1] in ['C','c']:
    f = 1.8 * float(val[0:-1]) + 32
    print("after the conversion: %.2fF"%f)
elif val[-1] in ['F','f']:
    c = (float(val[0:-1]) - 32) / 1.8
    print("after the conversion: %.2fC"%c)
else:
    print("input error!!")
>>> t="abcdefg"
>>> t[3]
'd'
>>> t[-3]
'e'
>>> t[1:3]
'bc'
>>> t[1:-3]
'bcd'
>>> "python" + ":" + t[0:3]
'python:abc'

Top-level program analysis:

  1. Young character length 7, 1st index 0 or -7, 1st index 6 or -1
  2. Inclusive of the passing route. Nyo t [1: 3], display one [0,3) interval
  3. Pass + can actually string skew connection
  4. Top-level val [0: -1], non-first-ranked characters after removal of display

3. Use turtle foot print snake, piecewise coloring

#Piecewise piecewise color painting
import turtle
def drawSnake(rad,angle,len,neckrad):
    for i in range(len):
        turtle.circle(rad,angle)
        if(i%2 == 0):
            turtle.pencolor("blue")
        else:
            turtle.pencolor("red")
        turtle.circle(-rad,angle)
    turtle.circle(rad,angle/2)
    turtle.fd(rd)
    turtle.circle(neckrad+1,180)
    turtle.fd(rad*2/3)

def main():
    turtle.setup(1300,800,0,0)
    pythonsize = 30
    turtle.pensize(pythonsize)
    turtle.seth(-40)
    drawSnake(40,80,5,pythonsize/2)

main()
  1. setup Graphic shape 窗 口, upper left corner 0,0 origin
  2. pensize setting motion 轨 迹 宽 degree
  3. seth setting motion time direction
  4. ʻimport turtle` method, but demand when using turtle.XX ()
  5. from turtle import *, can be used directly, the common function XX ()
  6. Taku exhibition, turtle foot painting single triangle, Shirosu Nyoshita (seth (0) horizontal right, 0 degree. Fd finger drawing line):
#Drawing triangle
import turtle
def main():
    turtle.setup(1300,800,0,0)
    pythonsize = 2
    turtle.pensize(pythonsize)
    
    turtle.seth(0)
    turtle.fd(90)

    turtle.seth(120)
    turtle.fd(90)

    turtle.seth(240)
    turtle.fd(90)

main()

image

4. Number type

Main explanations of this book 6 types of Python typology:

--Numeric character string type --Former group column type --Sentence type dictionary type

4.1 Typology

  1. Integer typology (0x9a / 0X9a, 0x open hexadecimal, 0b open 2 advance, 0o open 8 advance)
  2. Floating point type (like 0.0, -2.17, 96e4, 9.6E5), floating point accuracy given system correlation, use ʻimport sys sum sys.float_info`, pre-determination accuracy:
  3. Typological type (z = a + bj, a real number, b imaginary number part, a sum b capital floating point type, j standard for imaginary part. Nyo -5.6 + 7j .z.real imag sign imaginary part)
  4. Top three types can alternate phase conversion (int () / float () / complex ()), Nyo complex (4) = 4 + 0j
  5. Integer->> Floating-point number->> Recovery number, typological type, typological type
  6. type (z) Can be used as a fixed type.
  7. Regular Calculator Japanese Calculator Function:

image

4.2 Character string type

  1. Double quotation mark or single quotation mark
  2. Transforming code , Nyo comment Nakadai 码, Nyo print ("\" hello \ "") Export:" hello ".
  3. For index can question string specific position in skewer, related index operation, can reference Page3 intermediate solution
  4. Exclusion + No. Can advance character skewer for non-coupling, for reduction * Advance character skewer-like recovery
  5. len function return string skewer length
  6. Majority type, capital can pass str () convert
  7. Common character string skewer operation function available
  8. image
#General character string Kushibuki eradication line export
str="hell,world"
for i in str:
    print(i + "\n")
print("end")

>>> print("Hello\nWorld\n")
Hello
World

4.3 Original tuple

Immutable object, more safe

** Original concept: **

  1. Included in the original composition Multi-elemental typology, comma separation. T1 = 1,2,3, "hello"
  2. Former group can be empty, t2 = ()
  3. For former members can not be used ()
  4. Individual elemental element.

** Original features: **

  1. The existence of the element element, the relationship between the elements, the passage index, and the like t1 [0].
  2. Unable to renew after the original definition, and remove the impossible. Nyo t1 [0] = “hel”, encounter: TypeError: 'tuple' object does not support item assignment
  3. Kushikushi Ichiban, former group Nomaya Can + Japanese * No.

4.4 Column type [list]

** Column table concept: **

  1. Column list source group, element type can not be sample,
  2. Partially ordered set can index.
  3. However, there is no difference in the origin of the list, the size of the list is unlimited, and it can be repaired at any time. Column table Minor basic operation, similar to the character skewer operation

5. math 库 give random 库

5.1 math foot

5.2 random foot

>>> from random import *
>>> seed(2)
>>> uniform(1,10)
9.604308447003245
>>> uniform(1,10)
9.530447383534144
>>> uniform(1,10)
1.5089623095412783
>>> seed(2) 
>>> uniform(1,10)
9.604308447003245
>>> uniform(1,10)
9.530447383534144
>>> uniform(1,10)
1.5089623095412783

After the top surface has been set up, the number of random numbers will be randomized. Calculator Calculator Calculator, Impossible generation Authentic random number, Random number of Random numbers, Random number of seeds. Random seeds, seed () function, randomness, and system.

6. PI calculation (Monte Carlo method)

Pi irrational number, irrational formula can be calculated, PI-like calculation, approximate calculation method. Unit squares for all types of squares, large number of points, opposite points, possible inside or outside, the number of points that can be reached to a certain extent, the area of the area, the area of the area, the area of the area, the area of the area, the area of the area, and the area of the area. 圆 Inner score excluding 圆 Outer score ratio, immediate π / 4. The number of random points is large, and the pi is perfect.


from random import random
from math import sqrt
from time import clock
DARTS = 1200000
hits = 0
clock()
for i in range(1,DARTS):
    x,y = random(),random()
    dist = sqrt(x**2 + y**2)
    if dist <=1.0:
        hits = hits + 1
pi = 4 *(hits/DARTS)
print("pi-like%s"%pi)
print("Program time%-5.5ss"%clock())

Export consequences:

pi-like slogan 3.14148 Program time 2.655s

Caution:

  1. x, y = random (), random (), can 给 赋 值.
  2. Same walk 值: Example conversion x sum y 值, general method required change amount t, direct method conversion in python: x, y = y, x

Analysis example: image

Recommended Posts

[python] week1-3: Number type and operation
Python basic operation 3rd: Object-oriented and class
Python data structure and operation (Python learning memo ③)
Python and NumPy numeric type inheritance relationship
Python numeric type
[python] vector operation
Python OS operation
[Python] Matrix operation
Python2 string type
Python # string type
Correspondence summary of array operation of ruby and python
Prime number enumeration and primality test in Python
I compared "python dictionary type" and "excel function"
[Python] Class type and usage of datetime module
Basic operation of Python Pandas Series and Dataframe (1)
Python> Sort by number and sort by alphabet> Use sorted ()
[python] Compress and decompress
[Python] Operation of enumerate
Python and numpy tips
[Python] pip and wheel
Python callable type specification
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
[Python] Type Error: Summary of error causes and remedies for'None Type'
Ruby, Python and map
python input and output
Python and Ruby split
Python directory operation summary
Installing Python 3 on Mac and checking basic operation Part 1
Python logical operation stumbling
Python # How to check type and type for super beginners
Check Python # type identity
Python3, venv and Ansible
Python decorator operation memo
Prime number 2 in Python
Python asyncio and ContextVar
[python] Array slice operation
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
Get the MIME type in Python and determine the file format
Summary of Hash (Dictionary) operation support for Ruby and Python
Python Boolean operation return value is not always bool type
Programming with Python and Tkinter
Encryption and decryption with Python
Python: Class and instance variables
3-3, Python strings and character codes
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python indentation and string format
Python real division (/) and integer division (//)
Install Python and Flask (Windows 10)
About python objects and classes
[Python] Obtaining American-style week numbers
About Python variables and objects
Apache mod_auth_tkt and Python AuthTkt
Å (Ongustromu) and NFC @ Python
Python --Check type of values
S3 operation with python boto3
Understand Python packages and modules
# 2 [python3] Separation and comment out