python基础学习中常见问题
生活随笔
收集整理的這篇文章主要介紹了
python基础学习中常见问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、python for循環print不同層級的區別
方式1:
sum=0 for i in range(11):sum=sum+iprint(sum)?
輸出結果:
0 1 3 6 10 15 21 28 36 45 55?
方式2:
sum=0 for i in range(11):sum=sum+i print(sum)?輸出結果:
55?
2、定義int類型
猜數字游戲:
import random answer=random.randint(1,100) n=input("please input num(1-100):") while n!=answer:if n>answer:n=input("太大了!請重新輸入!")elif n<answer:n=input("太小了!請重新輸入!") print("你猜對了!")?報錯:
Traceback (most recent call last):File "/Users/gonghongwei/Desktop/if .py", line 5, in <module>if n>answer: TypeError: '>' not supported between instances of 'str' and 'int'?
這是因為input()返回的數據類型是str類型,不能直接和整數進行比較,必須先把str轉換成整型。
改正:
import random answer=random.randint(1,100) n=int(input("please input num(1-100):")) while n!=answer:if n>answer:n=int(input("太大了!請重新輸入!"))elif n<answer:n=int(input("太小了!請重新輸入!")) print("你猜對了!")?運行結果:
please input num(1-100):432 太大了!請重新輸入!33 太小了!請重新輸入!5 太小了!請重新輸入!45 太小了!請重新輸入!66 太大了!請重新輸入!7 太小了!請重新輸入!60 太小了!請重新輸入!50 太小了!請重新輸入!56 太小了!請重新輸入!60 太小了!請重新輸入!65 太大了!請重新輸入!64 你猜對了!?3、Python類實例
class Student():def __init__(self,name,city):self.name=nameself.city=cityprint("My name is %s and come from %s"%(name,city))def talk(self):print("Hello,everyone")stu1=Student('Jack','Beijing') stu1.talk() stu2=Student('Harry','Shanghai') stu2.talk()?運行結果:
My name is Jack and come from Beijing Hello,everyone My name is Harry and come from Shanghai Hello,everyone?
轉載于:https://www.cnblogs.com/gonghongwei/p/9249710.html
總結
以上是生活随笔為你收集整理的python基础学习中常见问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MapReduce的简单实例WordCo
- 下一篇: 一起用ipython