Python Programming

Lecture 1 Introduction

1.1 Course Intro

  • This is a basic course for Python programming.
  • “Life is short, you need Python.”

    by Bruce Eckel, ANSI C++ Comitee member

  • 什么是计算机“语言”?
  • 什么是编程?为什么要编程?
  • 为什么要数据分析?来源,精细化
  • 有很多程序设计语言,比如C,Java,Basic等等
  • 为什么要学Python?
    • 原因一:高级 (简单)
    • 原因二:普及,社区内容丰富
    • 原因三:强大,扩展性强
TIOBE 编程语言社区发布了 2019 年 9 月编程语言排行榜
TIOBE 预测:Python 将在 3-4 年内超越 Java 和 C

这门课主要涉及3个板块

  • 基本语法
  • 数据分析
  • 算法

课程要求

  1. 一共三次作业(6%*3=18%)
  2. 案例设计 (12%)
  3. 期末考试 (60%)
  4. 出勤率 (10%),课堂参与(Bonus)
  5. 答疑时间:Tuesday 14:00-15:00 or by appointment
  6. 联系方式
    • 邮箱: wang.lu@mail.shufe.edu.cn
    • 办公室:武东路校区商学院楼412室

主要教材

参考教材

  • 课件从哪里获取?
    • 我的网站:wangwanglulu.cn(如果你需要pdf格式文件,请在网址末尾加上?print-pdf,然后ctrl+p)。
    • 或者在上财教学网Blackboard系统上下载
  • 作业如何提交?
    • 作业为编程题,以电子版的方式提交
    • 作业的时限一般为两周
    • 提交到上财教学网Blackboard系统
    • 下次布置作业时会讲解作业的格式
  • 其他
    • 除课件外,我的网站上有与每次课相关的资料和课外阅读
    • 主要教材的代码下载与使用
    • 课件为reveal.js格式,如何使用

1.2 Python Intro

  • Python的简史,特色和安装

Python历史

Python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承。之所以选中Python作为程序的名字,是因为他是BBC电视剧——蒙提·派森的飞行马戏团(Monty Python's Flying Circus)的爱好者。

出自Wikipedia的Python

Python的特色

Python的设计哲学是“优雅”,“明确”,“简单”。Python开发者的哲学是“用一种方法,最好是只有一种方法来做一件事”。

出自Wikipedia的Python

废话不多说,上手试一下

Python的安装

  • 请使用Python 3.x (很多教材是2.x版本)
  • Anaconda,两种模式
  • 实际演示:第一个Python程序
    
    print("Hello, world!")
                
  • 第二个Python程序
    
    import antigravity
                
  • 第三个Python程序
    
    import this
                

1.3 程序设计的一些准则

  • 怎么把Python学好?

一些建议

  1. 初学者要勤写注释(什么是注释?)
  2. 遇到困难,自己勤查资料找办法解决问题(CSDN, stack overflow)
  3. 搞清楚需求,解决问题最重要
  4. 尽量写容易看明白的代码,尽量写少的代码
  5. 不要复制粘贴,一个字一个字的敲

注意几点

  1. 不要沉迷炫技
  2. 初学者不用太在意速度
  3. 不要参与网上无意义的争论
  4. 不要高估自己写的代码

最后请各位记住一点。。。

  • 编程终究只是“术”,是解决问题的工具
  • 这是你必须掌握的技巧,不是你追求的终极目标
  • 你的思考和创造力是最重要的

还有一点很遗憾。。。

即使学会了这门课,你还是不会“修电脑”。

1.4 Values

Three types of values

  • Integer
    • e.g., $1,2,15,-10$
  • Float
    • numbers with decimal point, e.g., $1.2, -3.8$.
    • for large or small numbers,
    • $5.91\times10^{10}=5.91e10$, $0.00233=2.33e-3$.
  • String
    • e.g., 'happy'

Python can tell you what type a value has.

>>> means what you input in the IPython console.


>>> type(4)
int

>>> type('Hello, World!')
str

>>> type(3.2)
float
Note: If numbers are in quotation marks, they are strings.

>>> type('17')
str

>>> type('3.2')
str

Escape string


>>> print('happy')
happy

If we want to print the single quotation marks?


>>> print("'happy'")
'happy'

If we want to print the double quotation marks?


>>> print('\"happy\"')
"happy"

If we want to print the slash?


>>> print('\\happy\\')
\happy\

If we want to print the double slashes?


>>> print(r'\\happy\\')
\\happy\\

Line break


>>> print('I\'m learning\nPython.')
I'm learning
Python.

Tab


>>> print('I\'m learning\tPython.')
I'm learning    Python.

>>> print('\\\n\\')
>>> print('\\\t\\')
>>> print(r'\\\t\\')

1.5 Variables

  • A variable is a name that refers to a value.

  • An assignment statement creates new variables and gives them values.

  • 
    >>> message = 'something'
    >>> n = 17
    >>> pi = 3.1415926535897931
    
  • To display the value of a variable, you can use a print statement.

  • 
    >>> print(n)
    17
    >>> print(pi)
    3.141592653589793
    
  • The type of a variable is the type of the value it refers to.

  • 
    >>> type(message)
    str
    >>> type(n)
    int
    >>> type(pi)
    float
    
  • Note that $=$ means "assignment", not equation.

  • 
    >>> x = 15
    >>> x = x + 10
    
  • Python is a Dynamically Typed Language. What is Dynamically Typed Language?

  • 
    >>> apple = 123 
    # apple is an integer
    >>> print(apple)
    123
    
    
    >>> apple = 'ABC' 
    # Now apple turns to be a string
    >>> print(apple)
    ABC
    
  • We can assign the value of a variable to another variable.

  • 
    >>> a = 'ABC'
    >>> b = a
    >>> print(b)
    ABC
    

Variable name

  • Variable names can be arbitrarily long. They are case sensitive.

  • You cannot start with a number.

  • It is common to use underscore character $\_$.

  • Spaces are not allowed in variable names, but underscores can be used to separate words in variable names.

  • Illegal name

  • 
    >>> 76trombones = 'big parade'
    SyntaxError: invalid syntax
    >>> more@ = 1000000
    SyntaxError: invalid syntax
    >>> class = 'Advanced Theory'
    SyntaxError: invalid syntax
    

Keywords

  • You cannot use the following keyword as variable names since they have been reserved by Python to recognize the structure of the program.

and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return

You would be better to use recognizable names. Check the following names.


a = 35.0
b = 12.50
c = a * b
print(c)

hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)

x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(x1q3p9afd)

Which ones are better?

1.6 Operators, input and output

Operators

  • $+,-,*,/,**$(exponentiation), %, //

  • Order of operations


>>> minute=50
>>> minute/20
2.5 #float

>>> minute=50
>>> minute//20 
2 #floored integer

>>> minute=50
>>> minute%20 
10 #remainder. This is useful!

>>> student_number=2017003425
>>> student_number//1000000
2017 
>>> student_number%10000
3425
  • String operations


>>> first=10
>>> second=15
>>> print(first+second)
25
>>> first='100'
>>> second='150'
>>> print(first + second)
100150

Input and Output

  • input() and print()

  • 
    >>> x = input()
    Some silly stuff
    >>> print(x)
    Some silly stuff
    
  • You can pass a string to input to be displayed to the user before pausing for input

  • Note: By using input(), the type of what the user inputs is always string!
  • 
    >>> name = input('What is your name?\n')
    What is your name?
    Chuck 
    >>> print(name)
    Chuck 
    #The type is string.
    
  • If you expect the user to type an integer, you can try to convert the return value to integer using the int() function

  • 
    >>> prompt = 'What is the speed?\n'
    >>> speed = input(prompt)
    What is the speed?
    17
    >>> int(speed)
    17
    >>> int(speed) + 5
    22
    
  • It may cause error, if the value cannot be converted.

  • 
    >>> speed = input(prompt)
    What is the speed?
    I do not know. #This is what you input.
    
    >>> int(speed)
    ValueError: invalid literal for int() with base 10:
    
  • For Editor, #output means the output of a sequence of code. Basically, the Editor is the same with IPython console.


age = 23
message = "Happy " + age + "rd Birthday!"
print(message)

#output
Traceback (most recent call last):
File "birthday.py", line 2, in <module>
message = "Happy " + age + "rd Birthday!"
TypeError: Can't convert 'int' object to str implicitly

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

#output
Happy 23rd Birthday!

1.7 Strings

Changing Case in a String with Methods
  • What is Method? (方法)
  • Is it the same with function? (函数)

name = "ada lovelace"
print(name.title())

#output
Ada Lovelace

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

#output
ADA LOVELACE
ada lovelace
Combining or Concatenating Strings

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)

#output
ada lovelace


print("Hello, " + full_name.title() + "!")

#output
Hello, Ada Lovelace!

Stripping Whitespace

  • To programmers 'python' and 'python ' look pretty much the same. But to a program, they are two different strings. To ensure that no whitespace exists at the right end of a string, use the rstrip() method.


>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '
  • However, it is only removed temporarily. To remove the whitespace from the string permanently, you have to store the stripped value back into the variable


>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python'
  • You can also strip whitespace from the left side of a string using the lstrip() method or strip whitespace from both sides at once using strip()


>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'

Summary

  • Course intro
  • Python intro
  • Tips for programming
  • Values, variables, operators, input and output, strings
  • Reading: Python for everybody Chapter 2