Python Basics - Basic

print('hello world') # Note that print is a function

Comment lines of code: Select Code, Ctrl + / using  '' '' ''  or  "" "" "" , the contents of the comment will need to be inserted therein

Compute

Numbers

- integers and floats.

Strings

#换行打印 """    """ 也可
s = '''This is a multi-line string.
This is the second line.''' 

silly_string = '''He said, "Aren't can't shouldn't wouldn't."'''
single_quote_str = 'He said, "Aren\'t can\'t shouldn\'t wouldn\'t."' # ' escaping 
double_quote_str = "He said, \"Aren't can't shouldn't wouldn't.\"" # " 

#format 方法
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))


#或者使用 %s
myscore = 1000  
message = 'I scored %s points' 
print(message % myscore) 

nums = 'What did the number %s say to the number %s? Nice belt!!' 
print(nums % (0, 8)) 

#字符串乘法
print(10 * 'a') 

List

Wherein the operating elements can be numbers, strings or lists

wizard_list [2] # third element 
wizard_list [2: 5] # third to fifth element 
mylist = [numbers, strings] # list is a list of two elements 
wizard_list.append ( 'bear burp') # in element added at the end 
del wizard_list [5] # deleted sixth element 

list3 = list1 + list2 # listing additive combiner [1, 2, 3, 4 , 'I', 'tripped', 'over', 'and', 'hit ',' The ',' Floor '] 
List1 = [. 1, 2] 
Print (List1 *. 5) # listing multiplication to give [. 1, 2,. 1, 2,. 1, 2,. 1, 2,. 1, 2] 

# List1 + 50 errors Zhibuding list there are strings 
# can not use the division (/) and subtraction (-) 
#That dumb Computer Things only sees in Black and white.Ask IT A Complicated Decision to the make, and throws up the ITS IT Hands with errors .

Tuples

A tuple is like a list that uses parentheses括号

The main difference between a tuple and a list is that a tuple cannot change once you’ve created it. 

If you create a tuple with two elements inside, it will always have those two elements inside.

fibs = (0, 1, 1, 2, 3) 

Map(each key maps to a particular value), 

In Python, a map (also referred to as a dict, short for dictionary) is a collection of things, like lists and tuples. Each item in a map has a key and a corresponding value. For example, say we have a list of people and their favorite sports:

favorite_sports = {'Ralph Williams' : 'Football','Michael Tippett' : 'Basketball','Edward Elgar' : 'Baseball'}

print(favorite_sports['Rebecca Clarke']) #打印值

del favorite_sports['Ethel Smyth'] #删除

favorite_sports['Ralph Williams'] = 'Ice Hockey' #更改值

The if statement

We combine conditions and responses into if statements. Conditions can be more complicated than a single question, and if statements can also be combined with multiple questions and different responses based on the answer to each question.

age = 13 
if age > 20:
    print('You are too old!')
#The lines following the colon must be in a block

A block of code is a grouped set of programming statements.

Each line in the block has four spaces at the beginning:

In Python, whitespace, such as a tab or a space, is meaningful. Code that is at the same position (indented the same number of spaces from the left margin) is grouped into a block, and whenever you start a new line with more spaces than the previous one, you are starting a new block that is part of the previous one, like this:

We group statements together into blocks because they are related. The statements need to be run together. When you change the indentation, you’re generally creating new blocks. 

Python expects you to use the same number of spaces for all the lines in a block. So if you start a block with four spaces, you should consistently use four spaces for that block. Here’s an example:

A condition is a programming statement that compares things and tells us whether the criteria set by the comparison are either True (yes) or False (no). For example, age > 10 is a condition, and is another way of saying, “Is the value of the age variable greater than 10?” We use symbols in Python (called operators) to create our conditions, such as equal to, greater than, and less than:

if-then-else statement /if and elif statements /Combining Conditions

if age == 12:      
    print("A pig fell in the mud!") 
else:        
    print("Shh. It's a secret.")


if age == 10:
    print("What do you call an unhappy cranberry?")
elif age == 11:
    print("What did the green grape say to the blue grape?")        
else:        
    print("Huh?")

if age == 10 or age == 11 or age == 12 or age == 13:
    print('What is 13 + 49 + 84 + 155 + 97? A headache!') 
else:        
    print('Huh?')

if age >= 10 and age <= 13:

an empty value is referred to as None, and it is the absence of value. And it’s important to note that the value None is different 

from the value 0 because it is the absence of a value, rather than a number with a value of 0. 

myval = None

Assigning a value of None to a variable is one way to reset it to its original, empty state. Setting a variable to None is also a way to define a variable without setting its value. You might do this when you know you’re going to need a variable later in your program, but you want to define all your variables at the beginning.

strings and numbers conversion

age = '10' 
converted_age = int(age)

age = '10.5' 
converted_age = float(age) 

age = 10
converted_age = str(age)

Loops cycle (for and while)

Range in X for (0,. 5): 
    Print ( 'Hello% S'% X) # Note that no comma oh

range函数用于创建数字列表 That may sound a little confusing. Let’s combine the range function with the list function to see exactly how this works. The range function doesn’t actually create a list of numbers; it returns an iterator, which is a type of Python object specially designed to work with loops. However, if we combine range with list, we get a list of numbers.

In the case of the for loop, the code is actually telling Python to do the following:

• Start counting from 0 and stop before reaching 5.

• For each number we count, store the value in the variable x. Then Python executes the block of code 

You don’t need to stick to using the range and list functions when making for loops. You could also use a list you’ve already created:

wizard_list = ['spider legs', 'toe of frog', 'snail tongue','bat wing', 'slug butter', 'bear burp'] 
for i in wizard_list:
    print(i)
#This code is a way of saying, “For each item in wizard_list, store the value in the variable i, and then print the contents of that variable.” 

ingredients = ['snails', 'leeches', 'gorilla belly-button lint','caterpillar eyebrows', 'centipede toes']
x=0;
for i in ingredients:
    x=x+1;
    print(x,'---',i)#原来打印的时候逗号隔开就是一个空格间隔了

Python expects the number of spaces in a block to be consistent. It doesn’t matter how many spaces you insert, as long as you use the same number for every new line

hugehairypants = ['huge', 'hairy', 'pants'] 
for i in hugehairypants:
    print(i) 
    for j in hugehairypants:
        print(j)         

for week in range(1, 53):
    coins = coins + magic_coins - stolen_coins
    print('Week %s = %s' % (week, coins))

 A for loop is a loop of a specific length, whereas a while loop is a loop that is used when you don’t know ahead of time when it needs to stop looping. 

while loop

x = 45 
y = 80
while x < 50 and y < 100:
    x = x + 1
    y = y + 1
    print(x, y)

1. Check the condition. 2. Execute the code in the block. 3. Repeat. 

Another common use of a while loop is to create semi-eternal loops. 

while True:    
    lots of code here    
    lots of code here    
    lots of code here    
    if some_value == True:    
        break

Reuse code code reuse

If you don’t reuse some of what you’re doing, you’ll eventually wear your fingers down to painful stubs through overtyping.

Reuse also makes your code shorter and easier to read. 

Using functions Functions

Functions are chunks of code that tell Python to do something. They are one way to reuse code—you can use functions in your programs again and again.

 

 

 Function has Three Parts A: A name, Parameters, and the function name parameter A body content.

# Defined functions 
DEF testFunc (myname): 
    Print ( 'Hello% S'% myname) 

DEF Savings (pocket_money, paper_route, Spending): 
    return pocket_money + paper_route - Spending # Return value 

another_variable = variable scopes within 100 # function only in function 
DEF the Variable_Test (): 
    first_variable = 10 
    second_variable = 20 is 
    return first_variable * second_variable * another_variable 

DEF spaceship_building (Cans): 
    total_cans = 0 
    for Week in Range (. 1, 53 is): 
        total_cans = total_cans + Cans 
        Print ( 'Week% S = Cans S% '% (Week, total_cans)) 

# call the function 
testFunc (' Mary ') #hello Mary 
Print (the Variable_Test ())  

The name of this function is testfunc. It has a single parameter, myname, and its body is the block of code immediately following the line beginning with def (short for define). A parameter is a variable that exists only while a function is being used. You can run the function by calling its name, using parentheses around the parameter value.

Functions can also be grouped together into modules, which is where Python becomes really useful, as opposed to just mildly useful.

Using Modules 

Modules are used to group functions, variables, and other things together into larger, more powerful programs. Some modules are built in to Python, and you can download other modules separately. 

You’ll find modules to help you write games (such as tkinter, which is built in, and PyGame, which is not), modules for manipulating images (such as PIL, the Python Imaging Library), and modules for drawing three-dimensional graphics (such as Panda3D). Modules can be used to do all sorts of useful things.

you could calculate the current date and time using a built-in module called time.

Here, the import command is used to tell Python that we want to use the module time. We can then call functions that are available in this module, using the dot symbol.For example, here’s how we might call the asctime function with the time module:

import time
print(time.asctime())
#The function asctime is a part of the time module that returns the current date and time, as a string

 

 

  

 

Guess you like

Origin www.cnblogs.com/icydengyw/p/12549477.html