1 PythonBasics
1 PythonBasics
Fall 2020
USIU-Africa
Hello World
●
We will use Idle to write and run our Python
programs. Typing idle at the command prompt.
●
Once launched, we can print the string “Hello
World!” like this:
2
Multi-line Strings
●
Notice on the previous slide that a string can be
limited by double or single qoutes.
●
A normal Python string goes on one line.
Breaking it produces an error. But a multiline
can span many lines
>>> s3 = "one
SyntaxError: EOL while scanning string literal
>>> s = """Welcome to
Python programming.
I hope that you
will enjoy yourself"""
>>>
3
Numbers
●
Python has two number types: integers and
floats.
●
Use + , -, *, and / to add, subtract, multiply, and
divide, respectively.
●
Use // for integer division and % for remainder
●
Python variables are not declared. The type is
inferred after the fact. You can check the type
like this: >>> a = 6
>>> type(a)
<class 'int'>
4
Repeating and Concatenating
Strings
●
To repeat a string, use the * operator.
●
To concatenate strings, use the + operator.
>>> "happy" * 3
'happyhappyhappy'
>>> s1 = "Hello"
>>> s2 = "World"
>>> s3 = s1 + " " + s2
>>> print(s3)
Hello World
5
Some Builtin Functions
●
To find the biggest number, use max
●
To find the length of a string use len
●
To convert a string into an int use int
●
To convert an int into a string use str
>>> 9 + 'th' + ' month'
>>> max(8, 7, 1, 9, 3) Traceback (most recent call last):
9 File "<pyshell#52>", line 1, in <module>
>>> len('September') 9 + 'th' + ' month'
9 TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> len('one') >>> str(9) +
3 SyntaxError: invalid syntax
>>> str(9) + 'th' + ' month'
'9th month'
6
Python Script
●
All the commands we typed at the Python shell
prompt can be put in a file called a script.
●
In Idle, go to the File menu and select New File
●
Type your Python statements and save your
script with a .py extension.
●
Click Run then Run Module (or press F5)
●
The output appears at the shell prompt.
7
Reading Input
8
Reading Numbers
9
Tutorials
●
Recommended Python Tutorials:
https://python.swaroopch.com/
http://anh.cs.luc.edu/python/hands-on/3.1/Hands
-onPythonTutorial.pdf
10