Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

What Is Python

Python is a popular programming language created by Guido van Rossum in 1991. It is used widely in web development, software development, data analysis, and mathematics. Key aspects covered in the document include Python variables and data types, operators, comments, functions, conditionals (if/else statements), lists and string methods.

Uploaded by

skylarzhang66
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

What Is Python

Python is a popular programming language created by Guido van Rossum in 1991. It is used widely in web development, software development, data analysis, and mathematics. Key aspects covered in the document include Python variables and data types, operators, comments, functions, conditionals (if/else statements), lists and string methods.

Uploaded by

skylarzhang66
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

What is Python?

Python is a popular programming language.


It was created by Guido van Rossum, and released in 1991.
● programming language
● Case-sensitive language → uppercase and lowercase is
completely different.
It is used for:
 web development (server-side)
 software development
 mathematics
 Data analysis

Variable
 Itcan vary → assign a value with it → Can always make
changes
E.g.)Variables in Python:
x=5
y = "Hello, World!"

Variable Names
 Variable Naming Rules:
1. Must start with a letter, or the underscore ( _ ).
2. Variable names can only contain alpha-numeric
characters (a-z), (0-9) and underscore. → Can’t start with
numbers. (A-z, 0-9, and _ )
3. Variable names are case sensitive. (age is different with
AGE)
4.Can't use keyword
(https://www.w3schools.com/python/python_ref_keywords.asp)
 E.g)
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Python symbols
 Assignment Operator:
(=): Used to assign a value to a variable.
(+=): variable = variable + value
E.g.) x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output will be 8
-= /= *= %= //=
 Arithmetic Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%) 100%17----15
Floor division(//) 100//17----5
Exponentiation (**) 5**3----125
 Comparison Operators:
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
 Logical Operators:
Logical AND (and)
Logical OR (or)
Logical NOT (not)
 Bools
True or False
 Colon (:)
 Period/Dot (.)
 Comma (,)
 Parentheses (( )): Used for grouping expressions and calling
functions.
 Square Brackets ([ ]): Used to define lists and access elements
in a list by index.----Position[0]start from 0
[-1]means the last one in the list
E.g.)mylist = [1,2,3]
print(mylist[0]+mylist[1])----3
print(mylist[-1])----3
 Curly Braces ({}): Used to define dictionaries and sets in
Python.
 Semicolon (;)
Python Comments
 Comment: #
 multi-line comments:""" """

Basic
‘ ’ or “ ”for text → String (str) → Need quotation mark →
Convert a number to string → b = str(2)
 Number → integer (int) → a = int(10)
 Float will give the number a point → c = float(5) → 5.0
 print(type(b)) → will tell us what they are → <class ‘str’>
 == → comparing the variable to see if it’s equal or not
 E.g.)
x=5
y = "John"
print(type(x))
print(type(y))
 E.g.)
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
 E.g.)
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Data Types
 Text Type: str
 Numeric Types: int, float, complex
 Sequence Types: list, tuple, range
 Mapping Type: dict
 Set Types: set, frozenset
 Boolean Type: bool
 Binary Types: bytes, bytearray, memoryvie
w
 None Type: NoneType
Getting the data type
You can get the data type of any object by using the type() function:

Lists-Indexing and Slicing


 [0]start from 0
 [-1]means the last one in the list
 [3:6]the ending is not including
 List index out of range
 E.g.)
 fruits=['apple', 'banana', 'orange', 'cherry', 'watermelon']
 print(fruit[0])----apple
print(fruit[-1])----watermelon
print(fruit[0:5:2])----['apple', 'orange', 'watermelon']
#2 is the step number 步长 ;[0:5:2]=[ : :2]

num=[1,2,3,4,5,6,7,8,9,10]
print(num[::4])----[1, 5, 9]
num=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
#6, 9, 12
print(num[5:12:3])
#Listmethods
 mylist1=[1,2,3]
 mylist1. append(4)#adding an new position as last position
 mylist1. pop()#removing the last position
 ylist1. reverse()#reverse the sequence of the list
 mylist.clear()#turn thelisttoemptylist
 mylist2=[1,5,-10,12,100,-100]
 mylist2.sort()#sorting the list from min to max, or a-z
 mylist2.extend(['a', 'b' ,'c'])#add another list to the og-list
 print(mylist1.insert(1#position,101#item))#add specific item
on specefic position (indexposition,value)
 print(mylist1.index(100))#the index position for the
parameter input
 mylist1.remove('a')#remove the selected item
 print(mylist.count('z'))#see how many same thing for select
edvalue
 mylist2=mylist1.copy()#copy the list values for other
purposes

#Stringmethods
 type( ), len()
 print(mystr. capitalize( )) #Converts the first character to
upper case
 print(mystr. count( )) #Returns the number of times a
specified value occurs in a string
 print(mystr. startwith/endwith( )) #Returns true if the string
start/ends with the specified value
 print(mystr. find( )) #Searches the string for a specified value
and returns the position of where it was found (find start
with“…)
#returns -1 if the value is not found
 print(mystr. replace('old value', 'new value', count)) #Returns
a string where a specified value is replaced with a specified
value
 print(mystr. lower( )) #Converts a string into lower case
 print(mystr. upper( )) #Converts a string into upper case
 print(mystr. isupper( )) #Returns True if the string follows the
rules of a title
 print(mystr. index( )) #Searches the string for a specified
value and returns the position of where it was found error #no
find
Function
a block of code which is designed to
You can pass data, known as parameters, into a function
A function can return data as a result
 Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
 Calling a Function
To call a function, use the function name followed by
parenthesis:
def my_function():
print("Hello from a function")
my_function()
 Arguments
1.)Information can be passed into functions as arguments.
2.)Arguments are specified after the function name, inside
the parentheses(). You can add as many arguments as you
want, just separate them with a comma.
def my_function(fname):
print(fname+"City")
my_function("Manchester")
my_function("Toronto")
my_function("Paris")
#Run:
Manchester City
Toronto City
Paris City

def mtof(m):
print(3.281*m, 'in feet')
mtof(2)
mtof(3)
#Run:
6.562 in feet
9.843 in feet
num1=int(input(' please enter the first number: '))
num2=int(input(' please enter the second number: '))
print(num1+num2)

def cal(num1,num2):
print(num1+num2)
cal(10,20)

#indentation 缩进

Output
def myfunction1():
print(1+1) #display the result in the console,without holding
valuesmyfunction1()
def myfunction2():
return 1+1 #return will hold the value from the function for
future usemyfunction2()

#return will exit future


no display in the terminal
hold/store the value with the function
( ) optional
#print() will not exit
display the result in the terminal
will not hold/store the value
( ) required

def myfunction3(a,b):
print(a+b)
myfunction3(myfunction2(),int(input('enter the b
number')))

def cal(a,b):
return a+b #nothing will be executed after return
keywordnum = cal(1,2)
return print

Will execute in the future( can Will not execute in the


assign to a value, you can use it future(the result only can
out of function) use in function)

No display the result(the code Yes


after return cannot be run)

Hold the value with function Will not hold the value

( )optional ( ) respond

Variable
#variable in the function
def sample():
global a
a=5
global b
b = 10 #local variable, can't be used outside the
function
print(a+b)
sample()
print(a+b)

Buit-in functions
print(max(1,2,3,10,100,100,-100))
print(min(1,2,3,10,100,100,-100))
print(abs(-10)) #absolute valueprint(pow(10,2))
#10**2print(sum([1,2,3,10,100,100,-100]))#sum up the
numbers within the list
print(sorted(['a','z','f','b']))
print(round(1.49)) #round up when >= 0.5
x = range(0,5) #Generate a sequence of numbers.
for i in x:
print(i)
Math methods----import math
print(math.pi)
print(math.floor(1.99)) #round
downprint(math.ceil(2.001))
#round up
print(math.pow(10,2))
print(math.trunc(10.9))#return the integer part of the
number
print(math.sqrt(100)) #square rootprint(math.sin(10))
print(math.tan(10))
print(math.cos(10))

Datetime methods----import datetime


x = datetime.datetime.now()
print(x)
print(x.year)
print(x.month)
print(x.day)
print(x.hour)
print(x.minute)
print(x.second)
print(x.microsecond)

If ... Else
 Python Conditions and If statements
 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 An "if statement" is written by using the if keyword.
 Exa=int(input('enter the first number:'))
b=int(input('enter the second number:'))
If a>b:
print('a is the bigger number')
elif b>a:
print('b is the bigger number')
else:
print('a and b are equal')
mark=int(input('enter the mark:'))
If mark >= 90:
print('A')
elif 90 > mark >= 80:
print('B')
elif 80 > mark >= 70:
print('C')
else:
print('D')

Import
 import datetime
 import math
 import random
 print(random.randint(5,10))#both numbers are inclusive
 print(random.randrange(0,11,3))#ending number not
inlcuded
 print(random.choice('hello'))#randomly pick on item from
list,tuple,str
 print(random.random()) #number between 0 and 1
 #change random.random() to 0 and 10, integer onlymylist =
[1,2,3,4,5]
 random.shuffle(mylist)#change the sequence inside the
sequence typeprint(mylist)

Python File
 Read ("r").
 Append ("a")
 Write ("w")
 Create ("x")
 Text mode ("t")
 Binary mode ("b")
 F.write('hello')
 os.remove('new.txt')

You might also like