0% found this document useful (0 votes)
4 views

1.VarStrNums

The document serves as an introduction to Python programming, covering fundamental concepts such as variables, strings, numbers, and control flow. It includes examples of variable assignment, string manipulation, arithmetic operations, and the use of conditional statements and loops. Additionally, it outlines best practices for naming variables and writing comments in code.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

1.VarStrNums

The document serves as an introduction to Python programming, covering fundamental concepts such as variables, strings, numbers, and control flow. It includes examples of variable assignment, string manipulation, arithmetic operations, and the use of conditional statements and loops. Additionally, it outlines best practices for naming variables and writing comments in code.

Uploaded by

gamer.guy123679
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

CSCI2040:

Introduction to Python: Variables,


Strings, and Numbers
Yim-Pan CHUI
Computer Science & Engineering Department
The Chinese University of Hong Kong

Derived from notebook prepared by John Lui for CSCI2040 1


Variable
• Let us try the famous "hello world"
1 print("Hello world")
2

Hello world

• Create and assign variable


1 message = "Hello to the wonderful world of Python"
2 print(message)

Hello to the wonderful world of Python

Derived from notebook prepared by John Lui for CSCI2040 2


Variable
• Let us try the famous "hello world"
1 message2 = "and welcome to CSCI2040"
2 print(message)
3 print(message2)

Hello to the wonderful world of Python


•and
Create andtoassign
welcome variable
CSCI2040

1 print(message, message2) # try to print both messages in one line


2

Hello to the wonderful world of Python and welcome to CSCI2040

Derived from notebook prepared by John Lui for CSCI2040 3


Comments
• # This line is a comment.
• Note that # can also be put after a computational statement

Good practices for comments


• It is short and to the point, but a complete thought.
• It explains your thinking, so that when you return to the code later you will
understand
• how you were approaching the problem.
• It explains your thinking, so that others who work with your code will
understand your overall approach.
• It explains particularly difficult sections of code in detail.

Derived from notebook prepared by John Lui for CSCI2040 4


Naming rules
1. Variables can only contain letters, numbers, and underscores. Variable
names can start with a letter or an underscore, but can not start with a
number.
2. Spaces are not allowed in variable names, so we use underscores instead
of spaces. For example, use student_name instead of "student name".
3. You cannot use Python keywords as variable names.
• Guidelines
• Variable names should be descriptive, without being too long. For example
mc_wheels is better than just "wheels", and number_of_wheels_on_a_motorcycle.
• Be careful about using the lowercase letter l and the uppercase letter O in
places where they could be confused with the numbers 1 and 0.

Derived from notebook prepared by John Lui for CSCI2040 5


Reserved Words
• Reserved words or keywords are names that have special
meaning in Python.

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Derived from notebook prepared by John Lui for CSCI2040 6
strings
1 my_string1 = "a string with a double quote"
2 my_string2 = 'a string with a single quote'
3 print ("STR1=", my_string1)
print ('STR2=', my_string2) # let's see the output

STR1= a string with a double quote


STR2= a string with a single quote

• what about a string which contains a quote?


1 quote = "Martin Luther King Jr. said, 'Free at last, free at last.'"
2 print (quote)

Martin Luther King Jr. said, 'Free at last, free at last.'


Derived from notebook prepared by John Lui for CSCI2040 7
Changing cases for the string
1 first_name = 'go'
2 print(first_name) # just print the string
3 print(first_name.title()) # capitalize the first letter
4 print(first_name.upper()) # capitalize the whole string

go
Go
GO
• Lower case as well
1 last_name = "Lamp"
2 print(last_name.lower())

lamp
Derived from notebook prepared by John Lui for CSCI2040 8
Combine strings - Concatenation
1 print ("Our king's first name is =", first_name)
2 print ("Our king's last name is =", last_name)
3 full_name = first_name + last_name
4 print ("Our king's name is = ", full_name)

Our king's first name is = go


Our king's last name is = Lamp
Our king's name is = goLamp
• Lower case as well
1 full_name1 = first_name.title() + " " + last_name
2 print ("Our king's full name is = ", full_name1)

Our king's full name is = Go Lamp


Derived from notebook prepared by John Lui for CSCI2040 9
Adding control characters into strings
1 print(full_name1, "is a jerk") # automatically add one space
2 print(full_name1, "\tis a jerk") # adding a tab
3 print(full_name1, "\t\t\tis a jerk!!!!") # adding 3 tabs
4
Go Lamp is a jerk
Go Lamp is a jerk
Go Lamp is a jerk!!!!
• New line
1 print(full_name1, "\nis a jerk")
2 print("\n",full_name1, "\n\t\tis a jerk")
Go Lamp
is a jerk

Go Lamp Derived from notebook prepared by John Lui for CSCI2040 10


is a jerk
Stripping white spaces
• In user input, they may inadvertently add more "white spaces" than
they intended to.
name = " CUHK " # a string with white spaces, before and after
print("stripping left of the string, name=" + " ***" + name.lstrip() + "***")
print("stripping right of the string, name=" + " ***" + name.rstrip() + "***")
print("stripping both sides of the string, name=" + " ***" + name.strip() + "***")

stripping left of the string, name= ***CUHK ***


stripping right of the string, name= *** CUHK***
stripping both sides of the string, name= ***CUHK***

Derived from notebook prepared by John Lui for CSCI2040 11


Strings
• type() and dir()
stuff = 'hello world'
type(stuff)
dir(stuff) # show all built-in functions of tyis type
help(stuff.capitalize) # show the meaning of the capitalize function
<class 'str'>
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Help on built-in function capitalize:

capitalize(...) method of builtins.str instance


S.capitalize() -> str

Return a capitalized version of S, i.e. make the first character


have upper case and the rest lower case.
Derived from notebook prepared by John Lui for CSCI2040 12
Numbers and numerics
• Integers
print (1+2.) # addition
print (3.-2) # subtraction
print (5*2.) # multiplication
print (8/4) # division
print (2.0**4) # exponentiation
print (2+3*4)
print ((2+3)*4)

3.0
1.0
10.0
2.0
16.0
14
20 Derived from notebook prepared by John Lui for CSCI2040 13
Numbers and numerics
• Floating points

print (0.1+0.1)
print (0.1+0.2)

0.2
0.30000000000000004

Derived from notebook prepared by John Lui for CSCI2040 14


Division in Python 2.7 and Python 3.X
• In Python 2.7; print 3/2 will give you 1
• In Python 3.X, print 3/2 will give you 1.5

• There are more differentiation between 3.X and 2.X for Python

Derived from notebook prepared by John Lui for CSCI2040 15


operators: +, -, , *, /, //, %

print(3+5) # adding two integers


print(3. + 5) # type conversion
print('Aaa' + 'Bbbbbb' +'CCC') # concatenation

8
8.0
AaaBbbbbbCCC

Derived from notebook prepared by John Lui for CSCI2040 16


print(-5.2) # gives a negative number -5.2
print(5-3) 2
print(2*3) 6
print('Lu'*2) # generate character strings LuLu
print(3**4) # power 81
print (3.0**4.) 81.0
print(5/3) 1.6666666666666667
print(5/3.) 1.6666666666666667
print(4//3) # gives floor 1
print(5.0//3.) 1.0
print (17 % 3) # gives remainder 2
print (17. % 3) 2.0

Derived from notebook prepared by John Lui for CSCI2040 17


Operator Description Examples

5 < 3 gives 0 (i.e. False) and 3 < 5 gives 1 (i.e. True).


< Less Than
Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True.

5 > 3 returns True. If both operands are numbers, they are first
> Greater Than converted to a common type. Otherwise, it always returns
False.
Less Than or
<= x = 3; y = 6; x <= y returns True.
Equal To
Greater Than
>= x = 4; y = 3; x >= 3 returns True.
or Equal To
x = 2; y = 2; x == y returns True. x = 'str'; y = 'stR'; x == y
== Equal To
returns False. x = 'str'; y = 'str'; x == y returns True.
!= Not Equal To x = 2; y = 3; x != y returns True.
not Boolean NOT x = True; not y returns False.
x = False; y = True; x and y returns False since x is False. In this
case, Python will not evaluate y since it knows that the value
and Boolean AND
of the expression will has to be false (since x is False). This is
called short-circuit evaluation.
x = True; y = False; x or y returns True. Short-circuit evaluation
or Boolean OR
applies here as well.
Introduction to Programming in Python 18
If statement
• Selection statement for 1 or more choices

if choice == 1:
print ('You choose Cola')
out = 'coke'
Only one outcome
elif choice == 2: is selected
print ('You choose Lemon tea')
out = 'Lemon Tea'
elif choice == 3:
print ('You choose Orange juice')
out = 'Orange Juice'
else:
print ('Invalid choice!')
print ('choose again')
Introduction to Programming in Python 19
If statement
• Selection statement for 1 or more choices

if choice == 1:
print ('You choose Cola') Note the : after each
out = 'coke'
elif choice == 2: Condition
print ('You choose Lemon tea')
out = 'Lemon Tea'
elif choice == 3: Also statements
indented are executed
print ('You choose Orange juice')
out = 'Orange Juice'
else:
print ('Invalid choice!')
for each choice
print ('choose again')

Introduction to Programming in Python 20


If statement
• All alternatives i.e. elif & else are optional.

if score >= 50:


print ('Passed')

• Or
if score >= 50:
print ('Passed!')
else:
print ('Failed!')
print ('Prepare for next test.')
Introduction to Programming in Python 21
Control Flow
a, b = 0, 1
Output
while b < 10: 1
print (b) 1
2
a, b = b, a+b 3
print ('END') 5
8
END

Introduction to Programming in Python 22


Control Flow
a, b = 0, 1 Multiple
while b < 10: assignments
print (b) a=0
a, b = b, a+b b=1
print ('END')
Assign at the
same time
Introduction to Programming in Python 23
Control Flow
a, b = 0, 1 Keep doing statements
in red box as long as
while b < 10: condition is true
print (b)
Note the ':' a must
a, b = b, a+b
print ('END')

Introduction to Programming in Python 24


Control Flow
a, b = 0, 1
while b < 10:
print (b)
a, b = b, a+b
print ('END')
Statements defined by
indentation
Introduction to Programming in Python 25
Control Flow
a, b = 0, 1
while b < 10: First time : b = 1
print (b) Enter loop
a, b = b, a+b print b
print ('END')
Output
1
Introduction to Programming in Python 26
Control Flow
a, b = 0, 1 First time : b = 1
while b < 10:
print (b) a update to 1
a, b = b, a+b b update to 0+1
print ('END')
Note: the two
Using old values of a & b
assignment update
at the same time
Introduction to Programming in Python 27
Control Flow
a, b = 0, 1
while b < 10: Program flow loop
print (b) to while and check
a, b = b, a+b condition again
print ('END')

Introduction to Programming in Python 28


Control Flow
a, b = 0, 1
while b < 10: 2nd time : b = 1
print (b) Enter loop
a, b = b, a+b print b
print ('END')
Output
1
1
Introduction to Programming in Python 29
Control Flow
a, b = 0, 1
while b < 10: 2nd time : b = 1
print (b)
a, b = b, a+b a update to 1
print ('END') b update to 1+1

Using old values of a & b

Introduction to Programming in Python 30


Control Flow
a, b = 0, 1
while b < 10: Program flow loop
print (b) to while and check
a, b = b, a+b condition again
print ('END')

Introduction to Programming in Python 31


Control Flow
a, b = 0, 1
while b < 10: 3rd time : b = 2
print (b) Enter loop
a, b = b, a+b print b
print ('END')
Output
1
1
2
Introduction to Programming in Python 32
Control Flow
a, b = 0, 1
while b < 10: 3rd time : b = 2
print (b)
a, b = b, a+b a update to 2
print ('END') b update to 2+1

Using old values of a & b

Introduction to Programming in Python 33


Control Flow
a, b = 0, 1
while b < 10: 4th time : b = 3
print (b) Enter loop
print b
a, b = b, a+b
print ('END') Output
1
1
2
3
Introduction to Programming in Python 34
Control Flow
a, b = 0, 1
while b < 10: 4th time : b = 3
print (b)
a, b = b, a+b a update to 3
print ('END') b update to 3+2

Using old values of a & b

Introduction to Programming in Python 35


Control Flow
a, b = 0, 1
5th time : b = 5
while b < 10:
Enter loop
print (b) print b
a, b = b, a+b
print ('END') Output
1
1
2
3
5
Introduction to Programming in Python 36
Control Flow
a, b = 0, 1
while b < 10: 5th time : b = 5
print (b)
a, b = b, a+b a update to 5
print ('END') b update to 5+3

Using old values of a & b

Introduction to Programming in Python 37


Control Flow
a, b = 0, 1
6th time : b = 8
while b < 10:
Enter loop
print (b) print b
a, b = b, a+b
print ('END') Output
1
1
2
3
5
8
Introduction to Programming in Python 38
Control Flow
a, b = 0, 1
while b < 10: 5th time : b = 8
print (b)
a, b = b, a+b a update to 8
print ('END') b update to 8+3
(now 11)

Introduction to Programming in Python 39


Control Flow
a, b = 0, 1 Program flow exit
while b < 10: loop as b< 10 is
print (b) now false
a, b = b, a+b Output
print ('END') 1
1
2
3
5
8
END
Introduction to Programming in Python 40
Control Flow

for x in range(0, 3) :
print (x) Output
0
1
2

Derived from notebook prepared by John Lui for CSCI2040 41


More on Flow Control, and
Output Formatting

42
Conditional Expressions
• In Python, there is a conditional expression construct similar to the
ternary operator in C.
• Syntax: var = true_value if condition else false_value

if condition:
which is equivalent to: var = true_value
else:
var = false_value
• Example:
a, b = 10, 20
if a < b:
a, b = 10, 20 min = a
min = a if a < b else b else :
print(min) # output 10 min = b
print(min) # output 10 43
Output Formatting using a string modulo
• Much like a printf()-style format as in C language, old formatting style
from Python 2
• Examples:
print('%s %s' % ('one','two'))

one two

b = 2.345
print('%02d %.2f' % (1,b))

01 2.35
44
Output Formatting using the format method
• Examples:
print('{} {}'.format('one','two'))

one two

b = 2
print('{} {}'.format(1,b))

1 2

45
Output Formatting using the format method
• With new style formatting, it is possible (and in Python 2.6 even
mandatory) to give placeholders an explicit positional index.
• This allows for rearranging the order of display without changing the
arguments.
This operation is not available
print('{1} {0}'.format('one','two'))
with old-style formatting.
two one

b = 2.345
print('{0} {1:5.2f}'.format(1,b))
1 2.35

46
Output Formatting using the format method
• Indeed, the placeholders can be identified by named indexes {price},
numbered indexes {0}, or empty braces {}.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 32.1))
For only 32.10 dollars!

txt1 = "My name is {fname}, I'am {age}".format(fname = "Noelle", age = 2.5)


txt2 = "My name is {0}, I'am {1}".format("Noelle", 2.5)
txt3 = "My name is {}, I'am {}".format("Noelle", 2.5)
print(txt1)
print(txt2) My name is Noelle, I'am 2.5
print(txt3) My name is Noelle, I'am 2.5
My name is Noelle, I'am 2.5 47

You might also like