Python从入门到高级(Python3) - 基础语法

Python从入门到高级(Python3)

1 print输入和注释的使用

print("Hello world!") # 结尾不需要分号, 打印字符串用单引号或双引号,
print('Hello world!') # 结果相同, 注释有两种, # 或 """ """
""" this is a comment, 
	这是多行注释 """ 

2 变量的使用

# Python program to declare variables 
# 变量可直接定义, 包括整数, 小数和字符串, 字符串可用单引号或双引号。
a = 3
print(a) 
b = 4.5
print(b)  
string_c ="helloworld"
print(string_c) 

3 列表

# 列表包含了数组和链表的功能
# 使用前需要建立
list_nums = []  
# append追加到结尾
list_nums.append(21) 
list_nums.append(40.5) 
list_nums.append("String") # 列表中可以有不同的数据结构
print(list_nums) 
# [21, 40.5, 'String']

4 input输出

# 输入字符窜
name = input("Enter username: ")  
print("hello", name) 
# 输入数字
num1 = int(input("Enter num1: ")) 
num2 = int(input("Enter num2: ")) 
num3 = num1 * num2 
print("Product is: ", num3) 

5 函数

# 无参函数
# 先定义后使用  
def hello(): # def: define + 函数名():
    print("hello") 
hello() # 直接调用
# calling function 
hello()

# main 函数的写法
# Python program to illustrate  
# function with main 
def getInteger(): 
    result = int(input("Enter integer: ")) 
    return result 
  
def Main(): 
    print("Started") 
  
    # calling the getInteger function and  
    # storing its returned value in the output variable 
    output = getInteger()      
    print(output) 
  
# now we are required to tell Python  
# for 'Main' function existence 
if __name__=="__main__": 
    Main() 

6 选择分支

# 选择分支结构, 需要注意不同的逻辑 
num1 = 30
if(num1<12): 
    print("Num1 is less than 12") 
elif(num1<35): # num1 >= 12 and num1 < 35
    print("Num2 is more than 12 and less than 35") 
else: # num1 >= 35
    print("Num2 is great than and equal to 35") 

7 for loop

for i in range(5): # range(0, 5)    
    print(i) 

8 module的使用

# 引用math module 
import math 
  
def Main(): 
    num = -85
  
    # fabs is used to get the absolute  
    # value of a decimal 
    num = math.fabs(num)  
    print(num) 
      
if __name__=="__main__": 
    Main() 

9 True and False

# in Python, True is 1 and False is 0 
print (False == 0) 
print (True == 1) 
print (True + True + True) 
print (True + False + False) 

True
True
3
1

10 None

a = None # None is a new datatype called NoneType, cannot eual to other data type
b = ""
print(a == b)
# False

11 and, not, or

print (None == 0) # not the same dataType
x = None
y = None
print (x == y) # same data type NoneType
print (True or False) # logic or
print (False and True) # logic and
print (not True) # logic not

False
True
True
False
False

12 删除del

a = [1, 2, 3] 
print ("The list before deleting any value") 
print (a) 
# 删除a[1]
del a[1] 
  
print ("The list after deleting 2nd element") 
print (a) 

The list before deleting any value
[1, 2, 3]
The list after deleting 2nd element
[1, 3]

13 assert 用于debug

# This function is used for debugging purposes. 
# Usually used to check the correctness of code. 
# If a statement evaluated to true, nothing happens, 
# but when it is false, “AssertionError” is raised . 
# One can also print a message with the error, separated by a comma.
# prints AssertionError 
assert 5 < 3, "5 is not smaller than 3" # 如果正确, 无报错
AssertionError                            Traceback (most recent call last)
<ipython-input-21-baf7e621687b> in <module>
      5 # One can also print a message with the error, separated by a comma.
      6 # prints AssertionError
----> 7 assert 5 < 3, "5 is not smaller than 3"

AssertionError: 5 is not smaller than 3

14 in and is

# in 用于判断是否在容器中, is 判断是否在同一地址
# using "in" to check  
if 's' in 'students': 
    print ("s is part of students") 
else :
    print ("s is not part of students") 
  
# using "in" to loop through 
for i in 'students': 
    print (i,end=" ") # end with a " "
  
print ("\r") # new line
      
# using is to check object identity 
# string is immutable( cannot be changed once alloted) 
# hence occupy same memory location 
print (' ' is ' ') 
  
# using is to check object identity 
# dictionary is mutable( can be changed once alloted) 
# hence occupy different memory location 
print ({
   } is {
   }) 
s is part of students
s t u d e n t s 
True
False

15 全局变量和局部变量

# global and non local 
  
#initializing variable globally 
a = 10
  
# used to read the variable 
def read(): 
    print (a) 
  
# changing the value of globally defined variable 
def mod1(): 
    global a  
    a = 5
  
# changing value of only local variable 
def mod2(): 
    a = 15
  
# reading initial value of a 
# prints 10 
read() 
  
# calling mod 1 function to modify value 
# modifies value of global a to 5 
mod1() 
  
# reading modified value 
# prints 5 
read() 
  
# calling mod 2 function to modify value 
# modifies value of local a to 15, doesn't effect global value 
mod2() 
  
# reading modified value 
# again prints 5 
read() 
10
5
5

16 nonlocal作用域大于global

print ("Value of a using nonlocal is : ",end="") 
def outer(): 
    a = 5
    def inner(): 
        nonlocal a  
        a = 10
    inner() 
    print (a) 
  
outer() 
  
# demonstrating without non local  
# inner loop not changing the value of outer a 
# prints 5 
print ("Value of a without using nonlocal is : ",end="") 
def outer(): 
    a = 5
    def inner(): 
        a = 10
    inner() 
    print (a) 
  
outer() 
Value of a using nonlocal is : 10
Value of a without using nonlocal is : 5

17 变量的作用区间

# var1 is in the global namespace  
var1 = 5
def some_func(): 
  
    # var2 is in the local namespace  
    var2 = 6
    def some_inner_func(): 
  
        # var3 is in the nested local  
        # namespace 
        var3 = 7
        
count = 5
def some_method(): 
    global count 
    count = count + 1
    print(count) 
some_method()
print(count)
# 6
# 6

def some_method(): 
    count = 5
    count = count + 5
    print(count) 
some_method() 
# 10

18 函数变量的作用范围

def some_func(): 
    print("Inside some_func") 
    def some_inner_func(): 
        var = 10
        print("Inside inner function, value of var:",var) 
    some_inner_func() 
    print("Try printing var from outer function: ",var) # NameError: name 'var' is not defined
some_func() 
Inside some_func
Inside inner function, value of var: 10

19 代码规范写法

Declared using Continuation Character (\):
s = 1 + 2 + 3 + \
    4 + 5 + 6 + \
    7 + 8 + 9

Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)

Declared using square brackets [] :
footballer = ['MESSI',
          'NEYMAR',
          'SUAREZ']

Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
     7 + 8 + 9}

Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4
j = 1
while(j<= 5): 
     print(j) 
     j = j + 1

20 多行代码

a = 10; b = 20; c = b + a 
print(a); print(b); print(c) 
10
20
30

21 print all the keyword

import keyword 
  
# printing all keywords at once using "kwlist()" 
print ("The list of keywords is : ") 
print (keyword.kwlist) 
The list of keywords is : 
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

22 advanced assign value in python

a = 1 if 20 > 10 else 0
  
# printing value of a 
print ("The value of a is: " + str(a)) 
# The value of a is: 1

23 print with end

print("geeks", end =" ") 
print("geeksforgeeks") 
  
# array 
a = [1, 2, 3, 4] 
  
# printing a element in same 
# line 
for i in range(4): 
    print(a[i], end =" ") 
geeks geeksforgeeks
1 2 3 4 

24 if statement

i = 10
if (i > 15): 
   print ("10 is less than 15") 
print ("I am Not in if") 

25 if else

i = 20; 
if (i < 15): 
    print ("i is smaller than 15") 
    print ("i'm in if Block") 
else: 
    print ("i is greater than 15") 
    print ("i'm in else Block") 
print ("i'm not in if and not in else Block") 

26 nested if

i = 10
if (i == 10): 
    #  First if statement 
    if (i < 15): 
        print ("i is smaller than 15") 
    # Nested - if statement 
    # Will only be executed if statement above 
    # it is true 
    if (i < 12): 
        print ("i is smaller than 12 too") 
    else: 
        print ("i is greater than 15") 

27 if…elif…else

i = 20
if (i == 10): 
    print ("i is 10") 
elif (i == 15): 
    print ("i is 15") 
elif (i == 20): 
    print ("i is 20") 
else: 
    print ("i is not present") 

28 shorthand if

# Python program to illustrate short hand if 
i = 10
if i < 15: print("i is less than 15") 

29 shorthand if else

# Python program to illustrate short hand if-else 
i = 10
print(True) if i < 15 else print(False) 

30 design a simple caculator

# Python program for simple calculator 
  
# Function to add two numbers  
def add(num1, num2): 
    return num1 + num2 
  
# Function to subtract two numbers  
def subtract(num1, num2): 
    return num1 - num2 
  
# Function to multiply two numbers 
def multiply(num1, num2): 
    return num1 * num2 
  
# Function to divide two numbers 
def divide(num1, num2): 
    return num1 / num2 
  
print("Please select operation: \n" \
        "1. Add\n" \
        "2. Subtract\n" \
        "3. Multiply\n" \
        "4. Divide\n") 
  
  
# Take input from the user  
select = int(input("Select operations form 1, 2, 3, 4 :")) 
  
number_1 = int(input("Enter first number: ")) 
number_2 = int(input("Enter second number: ")) 
  
if select == 1: 
    print(number_1, "+", number_2, "=", 
                    add(number_1, number_2)) 
  
elif select == 2: 
    print(number_1, "-", number_2, "=", 
                    subtract(number_1, number_2)) 
  
elif select == 3: 
    print(number_1, "*", number_2, "=", 
                    multiply(number_1, number_2)) 
  
elif select == 4: 
    print(number_1, "
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值