# 无参函数# 先定义后使用 defhello():# def: define + 函数名():print("hello")
hello()# 直接调用# calling function
hello()# main 函数的写法# Python program to illustrate # function with main defgetInteger():
result =int(input("Enter integer: "))return result
defMain():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 =30if(num1<12):print("Num1 is less than 12")elif(num1<35):# num1 >= 12 and num1 < 35print("Num2 is more than 12 and less than 35")else:# num1 >= 35print("Num2 is great than and equal to 35")
7 for loop
for i inrange(5):# range(0, 5) print(i)
8 module的使用
# 引用math module import math
defMain():
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)TrueTrue31
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 =Noneprint(x == y)# same data type NoneTypeprint(TrueorFalse)# logic orprint(FalseandTrue)# logic andprint(notTrue)# logic notFalseTrueTrueFalseFalse
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 assert5<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 defread():print(a)# changing the value of globally defined variable defmod1():global a
a =5# changing value of only local variable defmod2():
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="")defouter():
a =5definner():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="")defouter():
a =5definner():
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 =5defsome_func():# var2 is in the local namespace
var2 =6defsome_inner_func():# var3 is in the nested local # namespace
var3 =7
count =5defsome_method():global count
count = count +1print(count)
some_method()print(count)# 6# 6defsome_method():
count =5
count = count +5print(count)
some_method()# 10
18 函数变量的作用范围
defsome_func():print("Inside some_func")defsome_inner_func():
var =10print("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 =1while(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)
a =1if20>10else0# 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 inrange(4):print(a[i], end =" ")
geeks geeksforgeeks
1 2 3 4
24 if statement
i =10if(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 =10if(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 =20if(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 =10if i <15:print("i is less than 15")
29 shorthand if else
# Python program to illustrate short hand if-else
i =10print(True)if i <15elseprint(False)
30 design a simple caculator
# Python program for simple calculator # Function to add two numbers defadd(num1, num2):return num1 + num2
# Function to subtract two numbers defsubtract(num1, num2):return num1 - num2
# Function to multiply two numbers defmultiply(num1, num2):return num1 * num2
# Function to divide two numbers defdivide(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,"