美文网首页
Python快速入门

Python快速入门

作者: ForgetThatNight | 来源:发表于2018-07-09 22:34 被阅读21次

    Variables

    To assign the value 365 to the variable days, we enter the variable name, add an equals sign (=)

    days = 365
    
    days_1 = 365
    days_2 = 366
    
    number_of_days = 365
    number_of_days = 366
    
    print(365)
    
    number_of_days = 365
    print(number_of_days)
    

    输出 : 365

    Data Types

    When we assign a value an integer value to a variable, we say that the variable is an instance of the integer class

    The two most common numerical types in Python are integer and float

    The most common non-numerical type is a string

    str_test = "China"
    int_test = 123
    float_test = 122.5
    
    print(str_test)
    print(int_test)
    print(float_test)
    

    输出 :
    China
    123
    122.5

    print(type(str_test))
    print(type(int_test))
    print(type(float_test))
    

    输出 :
    <class 'str'>
    <class 'int'>
    <class 'float'>

    str_eight = str(8)  
    #str_eight + 10
    print (type(str_eight))
    eight = 8
    str_eight_two = str(eight)
    
    str_eight = "8"
    int_eight = int(str_eight)
    int_eight + 10
    print (type(int_eight))
    

    输出 :
    <class 'str'>
    <class 'int'>

    str_test = 'test'
    str_to_int = int(str_test)
    

    输出 :

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-42-175cd8fdcd31> in <module>()
          1 str_test = 'test'
    ----> 2 str_to_int = int(str_test)
    
    ValueError: invalid literal for int() with base 10: 'test'
    

    Comments

    print test

    """
    Addition: +
    Subtraction: -
    Multiplication: *
    Division: /
    Exponent: **
    """
    

    输出 : '\nAddition: +\nSubtraction: -\nMultiplication: *\nDivision: /\nExponent: **\n'

    china=10
    united_states=100
    china_plus_10 = china + 10
    us_times_100 = united_states * 100
    print(china_plus_10)
    print(us_times_100)
    print (china**2)
    

    输出 :
    20
    10000
    100

    #LIST
    months = []
    print (type(months))
    print (months)
    months.append("January")
    months.append("February")
    print (months)
    

    输出 :
    <class 'list'>
    []
    ['January', 'February']

    months = []
    months.append(1)
    months.append("January")
    months.append(2)
    months.append("February")
    print (months)
    

    输出 : [1, 'January', 2, 'February']

    temps = ["China", 122.5, "India", 124.0, "United States", 134.1]
    
    countries = []
    temperatures = []
    
    countries.append("China")
    countries.append("India")
    countries.append("United States")
    
    temperatures.append(30.5)
    temperatures.append(25.0)
    temperatures.append(15.1)
    
    print (countries)
    print (temperatures)
    china = countries[0]
    china_temperature = temperatures[1]
    print (china)
    print (china_temperature)
    

    输出 :
    ['China', 'India', 'United States']
    [30.5, 25.0, 15.1]
    China
    25.0

    int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    length = len(int_months) # Contains the integer value 12.
    print (length)
    

    输出 : 12

    int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    index = len(int_months) - 1
    last_value = int_months[index] # Contains the value at index 11.
    print (last_value)
    print (int_months[-1])
    

    输出 :
    12
    12

    #Slicing 
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
    # Values at index 2, 3, but not 4.
    two_four = months[2:4]
    print (two_four)
    

    输出 : ['Mar', 'Apr']

    three_six = months[3:]
    print (three_six)
    

    输出 : ['Apr', 'May', 'Jun', 'Jul']

    #Files
    #To open a file in Python, we use the open() function
    f = open("test.txt", "r")
    
    g = f.read()
    print(g)
    
    f.close()
    

    输出 :
    hello python
    tangyudi 123
    ML 456
    DL 789
    data 234

    f = open("test_write.txt", "w")
    
    f.write('123456')
    f.write('\n')
    f.write('234567')
    
    f.close()
    
    # We can split a string into a list.
    sample = "john,plastic,joe"
    split_list = sample.split(",")
    print(split_list)
    
    # Here's another example.
    string_two = "How much wood\ncan a woodchuck chuck\nif a woodchuck\ncould chuck wood?"
    split_string_two = string_two.split('\n')
    print(split_string_two)
    
    # Code from previous cells
    f = open('test.txt', 'r')
    data = f.read()
    rows = data.split('\n')
    print(rows[0:3])
    

    输出 :
    ['john', 'plastic', 'joe']
    ['How much wood', 'can a woodchuck chuck', 'if a woodchuck', 'could chuck wood?']
    ['hello python', 'tangyudi 123', 'ML 456']

    #loop
    cities = ["Austin", "Dallas", "Houston"]
    for city in cities:        
        print(city)
    print ('123')
    

    输出 :
    Austin
    Dallas
    Houston
    123

    i = 0
    while i < 3:
        i += 1
        print (i)
    

    输出 :
    1
    2
    3

    for i in range(15):
        print (i)
    

    输出 :
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    cities = [["Austin", "Dallas", "Houston"],['Haerbin','Shanghai','Beijing']]
    #print (cities)
    for city in cities:
        print(city)
        
    
    for i in cities:
        for j in i:
            print (j)
    

    输出 :
    ['Austin', 'Dallas', 'Houston']
    ['Haerbin', 'Shanghai', 'Beijing']
    Austin
    Dallas
    Houston
    Haerbin
    Shanghai
    Beijing

    #Booleans
    
    cat = True
    dog = False
    print(type(cat))
    

    输出 : <class 'bool'>

    print(8 == 8) # True
    print(8 != 8) # False
    print(8 == 10) # False
    print(8 != 10) # True
    
    print ("abc" == "abc")
    print (["January", "February"] == ["January", "February"])
    print (5.0 == 5.0)
    

    输出 :
    True
    False
    False
    True
    True
    True
    True

    rates = [10, 15, 20]
    
    print (rates[0] > rates[1]) # False
    print (rates[0] >= rates[0]) # True
    

    输出 :
    False
    True

    #If Statements
    sample_rate = 700
    greater = (sample_rate > 5)
    if 0:                    #This is the conditional statement.
        print(sample_rate)
    else:
        print('less than')
    

    输出 : less than

    t = True
    f = True
    
    if t:
        print("Now you see me")
    if f:
        print("Now you don't")
    

    输出 :
    Now you see me
    Now you don't

    f = open('dq_unisex_names.csv', 'r')
    names = f.read()
    names_list = names.split('\n')
    first_five = names_list[0:5]
    print (first_five)
    

    输出 : ['Casey,176544.3281', 'Riley,154860.6652', 'Jessie,136381.8307', 'Jackie,132928.7887', 'Avery,121797.4195']

    #Convert The List Of Strings To A List Of Lists
    f = open('dq_unisex_names.csv', 'r')
    names = f.read()
    names_list = names.split('\n')
    nested_list = []
    for line in names_list:
        comma_list = line.split(',')
        nested_list.append(comma_list)
    print(nested_list[0:5])
    

    输出 :
    [['Casey', '176544.3281'], ['Riley', '154860.6652'], ['Jessie', '136381.8307'], ['Jackie', '132928.7887'], ['Avery', '121797.4195']]

    nested_list = [['Casey', '176544.3281'], ['Riley', '154860.6652'], ['Jessie', '136381.8307'], ['Jackie', '132928.7887'], ['Avery', '121797.4195']]
    numerical_list = []
    for line in nested_list:
        name = line[0]
        count = float(line[1])
        new_list = [name, count]
        numerical_list.append(new_list)
    print(numerical_list[0:5])
    

    输出 :
    [['Casey', 176544.3281], ['Riley', 154860.6652], ['Jessie', 136381.8307], ['Jackie', 132928.7887], ['Avery', 121797.4195]]

    weather_data = []
    f = open("la_weather.csv", 'r')
    data = f.read()
    rows = data.split('\n')
    #print (rows)
    for row in rows:
        split_row = row.split(",")
        weather_data.append(split_row)
    print (weather_data)
    

    输出 :
    [['1', 'Sunny'], ['2', 'Sunny'], ['3', 'Sunny'], ['4', 'Sunny'], ['5', 'Sunny'], ['6', 'Rain'], ['7', 'Sunny'], ['8', 'Sunny'], ['9', 'Fog'], ['10', 'Rain']]

    weather = []
    for row in weather_data:
        weather.append(row[1])
    print (weather)
    f.close()
    

    输出 :
    ['Sunny', 'Sunny', 'Sunny', 'Sunny', 'Sunny', 'Rain', 'Sunny', 'Sunny', 'Fog', 'Rain']

    #find a value
    animals = ["cat", "dog", "rabbit"]
    for animal in animals:
        if animal == "cat":
            print("Cat found")
    

    输出 : Cat found

    animals = ["cat", "dog", "rabbit"]
    if "cat" in animals:
        print("Cat found")
    

    输出 : Cat found

    animals = ["cat", "dog", "rabbit"]
    cat_found = "cat" in animals
    print (cat_found)
    

    输出 : True

    #Dictionaries
    students = ["Tom", "Jim", "Sue", "Ann"]
    scores = [70, 80, 85, 75]
    
    indexes = [0,1,2,3]
    name = "Sue"
    score = 0
    for i in indexes:
        if students[i] == name:
            score = scores[i]
    print(score)
    

    输出 : 85

    scores = {} #key value
    print (type(scores))
    scores["Jim"] = 80
    scores["Sue"] = 85
    scores["Ann"] = 75
    #print (scores.keys())
    print (scores)
    print (scores["Sue"])
    

    输出 :
    <class 'dict'>
    {'Ann': 75, 'Sue': 85, 'Jim': 80}
    85

    students = {}
    students["Tom"] = 60
    students["Jim"] = 70
    print (students)
    
    students = {
        "Tom": 60,
        "Jim": 70
    }
    print (students)
    

    输出 :
    {'Tom': 60, 'Jim': 70}
    {'Tom': 60, 'Jim': 70}

    students = {
        "Tom": 60,
        "Jim": 70
    }
    students["Tom"] = 65
    print (students)
    students["Tom"] = students["Tom"] + 5
    print (students)
    

    输出 :
    {'Tom': 65, 'Jim': 70}
    {'Tom': 70, 'Jim': 70}

    students = {
        "Tom": 60,
        "Jim": 70
    }
    print ('Tom' in students)
    

    输出 : False

    pantry = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"]
    pantry_counts = {}
    
    for item in pantry:
        if item in pantry_counts:
            pantry_counts[item] = pantry_counts[item] + 1
        else:
            pantry_counts[item] = 1
    print (pantry_counts)
    

    输出 : {'potato': 1, 'apple': 3, 'tomato': 1, 'orange': 2, 'grape': 2}

    def printHello():
        
        print ('hello python')
        
    def printNum():
        
        for i in range(0,10):
            print (i)
        return
            
    def add(a,b):
        return a+b
        
    #printHello()
    #print (printNum())
    print (add(1,2))
    

    输出 : 3

    def printHello():
        print ('hello')
        
    def printNum():
        for i in range(0,10):
            print (i)
        return
            
    def add(a,b):
        return a+b
        
    print (printHello())
    print (printNum())
    print (add(1,2))
    

    输出 :

    hello
    None
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    None
    3
    

    相关文章

      网友评论

          本文标题:Python快速入门

          本文链接:https://www.haomeiwen.com/subject/oxyouftx.html