Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

1

CHAPTER 1:
INTRODUCTION TO PYTHON
2

CHAPTER OUTCOMES

• The learning objectives of this course are:

• To understand why Python is a useful scripting language for developers.

• To learn how to design and program Python applications.

• To learn how to write loops and decision statements in Python.

• To learn how to use lists, tuples, and dictionaries in Python programs.


3

PART 1 – BASIC CONCEPTS


4

WHAT IS PYTHON?

• A modern interpreted programing


language, created in 1991 by Guido van
Rossum.
• Known for requiring less code to
accomplish tasks than other languages
Principles:
• Allows programmer to be Simple
• Allows programmer Complexity, without
being complicated
• Readable
5

BASIC CONCEPTS:
Comment
display output to the user
#This is my first program "Hello World!" You can use single quotes
print ("Teacher says: Hello World!") or double quotes
""" This would be a multi line comment
in Python that spans several lines and Multi line
describes your code, your day, or anything you want it Comment
to"""
print ('I said to the class "sometimes you need to
shutdown and restart a notebook when cells refuse to
run"')
print("It's time to save your code")

Output:
Teacher says: Hello World!
I said to the class "sometimes you need to shutdown and restart a notebook when cells refuse to run"
It's time to save your code
6

VARIABLES
• In Python variables are used to store values.
• The type of data stored is called the data type of the variable.
• Three common data types:

String (str) Integer (int) Float (float)


A series of letters, numbers, and A whole number- no decimals. A decimal number.
spaces. Always enclosed in
quotes
VARIABLE ASSIGNMENT
• To give a variable a value we use an assignment statement.
• Do not give the variable a type. The interpreter will decide type based on
the value entered.

varName = value
Message = "This is a string of data"

Variables are case sensitive! Num1 and num1 are NOT the same variable!
8

EXERCISE 1

Why does this error occur? What is the output ?


message1 = "This is some data"
num1 = "2"
message2 = " that we must discuss"
num2 = 1
message3 = message1+ message2
num3 = num1 + num2
print(message3)
Output:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/CS120/Example1.py", line 3, in
<module>
Output:
num3 = num1 + num2 This is some data that we must discuss
TypeError: Can't convert 'int' object to str implicitly

Process finished with exit code 1

The quotes make all the difference! Num1 is a Strings can be added together. This is called
string. Strings cannot be added to integers. concatenation.
9

EXERCISE 2

What is the output ?

message = "This is a python course"


message1 = "What is your name?"
print(message)
print(message1+ " =Justin")

Output:
This is a python course
What is your name? =Justin
10

VARIABLE REASSIGNMENT

• To give a variable a new value simple write a new assignment


statement. New value will overwrite the old value.

num1 = 6
print (num1) Output:
6
num1 = 8
8
print(num1)
11

TYPE() FUNCTION
• Returns the data type of the given data or variable

a = 5
print (type(a)) Output:
<class 'int'>
ch = 'this is a message'
<class 'str'>
print (type(ch))
12

INPUT FUNCTION
• In Python use the input() function to gather input from the user
name1 = input("enter your name: ")
print (name1)

Input always returns a data type of string

The in keyword allows a simple search to be preformed.


in returns a Boolean result on if the searched text is contained in a string.

message = input("What is your name?") Output:


print("Eric" in message) What is your name? Eric
True
13

INPUT FUNCTION – EXERCISE 3


print("Please enter five grades. One at a time")
grade1=input("Grade 1:")
grade2=input("Grade 2:")
grade3=input("Grade 3:")
grade4=input("Grade 4:")
grade5=input("Grade 5:")
sum_grades=int(grade1)+int(grade2)+int(grade3)+int(grade4)+int(grade5)
print(sum_grades)

Output:
Please enter five grades. One at a time
Grade 1:10 To cast a data type – use the
Grade 2:12 specific Type keyword ( like int
Grade 3:11 or str) in front of the variable or
Grade 4:10
Grade 5:7
data
50
14

PRINT FORMATTING
print(object(s), separator=separator, end=end, file=file, flush=flush)

Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed
sep='separator' Optional. Specify how to separate the objects, if there is more than one.
Default is ''
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
file Optional. An object with a write method. Default is sys.stdout
flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False
15

PRINT FORMATTING – EXAMPLE 1


print("Please enter five grades. One at a time")
grade1=input("Grade 1:")
grade2=input("Grade 2:")
grade3=input("Grade 3:")
grade4=input("Grade 4:")
grade5=input("Grade 5:")
sum_grades=int(grade1)+int(grade2)+int(grade3)+int(grade4)+int(grade5)
average=sum_grades/5
print("The average is:", str(average) + ".")

Output:
Please enter five grades. One at a time
Grade 1:10
Grade 2:12 comma (,) method combines printable items
Grade 3:11 with a space
Grade 4:10
Grade 5:7
The average is: 10.0.
16

PRINT FORMATTING – EXAMPLE 2


Output:
print("Hello", "how are you?", sep=" --- ")
Hello --- how are you?

Output:
print("Hello" , "how are you?", sep=" --- ", end ="***") Hello --- how are you?***

print("Hello" , "how are you?", sep="\t", end ="\n") Output:


Hello how are you?
print("Stop") Stop
17

STRING – EXAMPLE 1
Ch= P y t h o n
index 1 0 1 2 3 4 5

index 2 -6 -5 -4 -3 -2 -1

ch="python" Output:
print(ch[0]) p
print(ch[-1]) n
print(ch[-6]) p
print(ch[1:3]) yt
print(ch[:4]) pyth
print(ch[2:]) thon
print(ch[::2]) pto
print(ch[::-1]) nohtyp
print(ch[::-2]) nhy
print(ch*2) pythonpython
ch[1]='b' TypeError: 'str' object does not support item assignment
18

STRING – TESTS

.isalpha() Returns True if a string is an alphabetical character a-z, A-Z


.isalnum() Returns True if there is at least 1 character and all are alphabetical or
digits
.istitle() Tests to see if the string is title (all words capitalized)
.isdigit() Tests to see if the string is made entire of digits.
.islower()
These check for all uppercase or lowercase characters
.isupper()
.startswith() This method returns True if a string starts with the specified prefix(string). If
not, it returns False.
19

STRING – EXAMPLE 2
ch ="python"
ch1="343"
ch2="A Cold Stromy Night"
ch3= "WELCOME TO THE JUNGLE" Output:
print (ch.isalpha()) True
print (ch1.isalpha()) False
print (ch.isalnum()) True
print (ch1.isalnum()) True
print (ch2.istitle()) True
print (ch3.istitle()) False
print (ch1.isdigit()) True
print ("3rd".isdigit()) False
print (ch3.isupper()) True
print (ch.islower()) True
print ("THIS IS A MESSAGE WITH 214565".isupper()) True
print (ch.startswith("p")) True
print (ch2.startswith("a")) False
20

STRING – FUNCTIONS
.capitalize() capitalizes the first character of a string
.lower() all characters of a string are made lowercase
.upper() all characters of a string are made uppercase
.swapcase() all characters of a string are made to switch case upper becomes lower
and vice versa
.title() each 'word' separated by a space is capitalized
.find() The find() method returns the index of first occurrence of the substring (if
found). If not found, it returns -1.
.count() The string count() method returns the number of occurrences of a substring
in the given string.
.replace() The replace() method returns a copy of the string where all occurrences of
a substring is replaced with another substring.
21

STRING – EXAMPLE 3
message=input("Please type your name: ").upper() Output:
Please type your name: Alton
print(message)
ALTON
print(message.lower()) alton

message="introduction to python" Output:


print(message.capitalize()) Introduction to python
print(message.title()) Introduction To Python

message = 'Hello world' Output:


print(message.find('world')) 6
print(message.count('o')) 2
print(message.replace('Hello','Hi')) Hi world
print (message.swapcase()) hELLO WORLD
22

STORING NUMBER
addition +
subtraction -
Multiplication *
Division /
Exponent **
Modulo %

Order: (), **, * or /, + or -


Multiple line
total=5+6**2+8\
total=5+6**2+8+6+2 Output:
+6+2
print(total) 57
print(total)
23

NUMBER FORMAT
Output:
print('I have %d cats' %6) I have 6 cats
print('I have %3d cats' %6) I have 6 cats
print('I have %03d cats' %6) I have 006 cats
print('I have %f cats' %6) I have 6.000000 cats
print('I have %.2f cats' %6) I have 6.00 cats
print('I have %s cats' %6) I have 6 cats
print('I have {0:d} cats'.format(6)) I have 6 cats
print('I have {0:3d} cats'.format(6)) I have 6 cats
print('I have {0:03d} cats'.format(6)) I have 006 cats
print('I have {0:f} cats'.format(6)) I have 6.000000 cats
print('I have {0:.2f} cats'.format(6)) I have 6.00 cats

You might also like