安裝Python環(huán)境
Python的版本
-Python2.x
-Python3.x
注:Python2.x與Python 3.x不兼容
Python中變量的命名方式
1、駝峰式命名法
大駝峰 --UserNameInfo
小駝峰 -- userNameInfo
2家凯、下滑線命名
下劃線:user_name_info
注:可以使用中文命名冒滩,但是不建議:
變量1 = 'hehe'
print(變量1)
在java中交換變量與在Python中交換變量的區(qū)別
1.在java中交換變量
a = 100
b = 1000
temp = 0
temp = a
a = b
b = temp
print(a, b)
2.在Python中交換變量
a, b = b, a
print(a, b)
Python中的判斷語句
1、Python中的if else語句:
if 要滿足的條件:
滿足條件要執(zhí)行的事情
else:
不滿足條件要執(zhí)行的事情
eg:
age = 8
print(type(age))
age = int(age)
print(type(age))
if age >= 18:
print('恭喜你成年了袭蝗,可以去網(wǎng)吧了')
else:
print('對不起,你還是個寶寶')
2、Python中的elif語句:
if xxx1:
滿足xxx1條件時要執(zhí)行的事情
elif xxx2:
滿足xxx2條件時要執(zhí)行的事情
elif xxx3
注:Python中的elif相當(dāng)于switch赂弓,elif必須與if一起使用,另外哪轿,如果需要可以加上else:
eg:
score=34
if score>=90 and score<=100:
print('您的成績等級為A')
elif score>=80 and score<90:
print('您的成績等級為B')
elif score>=70 and score<80:
print('您的成績等級為C')
elif score>=60 and score<70:
print('您的成績等級為D')
elif score<60:
print('您的成績等級為不及格')
python中的循環(huán)語句
1盈魁、while循環(huán):
while 要判斷的條件:
循環(huán)體
eg:
1.1 計算 1 ~ 100之間的累加和
i = 1
sum_num = 0
while i <= 100:
sum_num = sum_num + i
sum_num += i
i += 1
print(sum_num)
1.2 當(dāng)累加和大于 1000時跳出循環(huán)(使用break跳出本層循環(huán))
i = 1
sum = 0
while i <= 100:
sum += i
if sum > 1000:
break
i += 1
print(sum)
1.3 計算所有奇數(shù)的和(使用continue跳出本次循環(huán))
i = 1
sum = 0
while i <= 100:
if i % 2 == 0:
i += 1
continue
sum += i
i += 1
print(sum)
2、for循環(huán):
for 臨時變量 in 可迭代對象:
循環(huán)體
eg:
2.1 找出neusoft中的x:
for x in 'neusoft':
print(x)
2.2 給你女朋友道歉100次:
for i in range(1,101):
print('對不起窃诉,我錯了杨耙,這是我第{}次向你道歉'.format(i))
猜數(shù)字游戲案例
from random import randint
max_num = int(input('請您輸入要猜數(shù)字的最大值'))
min_num = int(input('請您輸入要猜數(shù)字的最小值'))
computer_num = randint(min_num, max_num)
count = 0
while True:
count += 1
guess_num = int(input('來了老弟赤套,請輸入您要猜的數(shù)字'))
if guess_num < computer_num:
print('您猜小了哦')
elif guess_num > computer_num:
print('您猜大了')
else:
if count == 1:
print('這是高手,{}次竟然就猜對'.format(count))
elif count >= 2 and count <= 5:
print('你也太厲害吧, {}次猜對了'.format(count))
else:
print('你也太菜了珊膜,{}次才猜對容握,洗洗睡吧'.format(count))
break