Python Programming Basics Guide
Python Programming Basics Guide
Python Basics
CS1302 Introduction to Computer Programming
%reload_ext divewidgets
Content
Syntax, Comments, Literal, Variable, Function, Identifier
Basic data types
string formatting
Syntax
In computer science, the syntax is a set of rules for programming. In other
words, it means using legal structures and commands that a computer can
interpret.
Human language is used to communicate with people. Programming language is
used to communicate with machine. If we don't follow the correct syntax, the
computer can't run the code (syntax error). See example below.
In [2]: # print() is a function to print a message out on the screen
print("Hello, World!" #this line has error because it misses one ) in the
^
SyntaxError: incomplete input
# Fixed solution:
```python
print("Hello, World!")
```
# Explanation of changes:
* **Added a closing parenthesis**: Added a closing parenthesis at the en
d of the `print()` function call to complete the syntax.
Alternatively, you can also test the code in an interactive Python shell
or a Jupyter notebook. Simply copy and paste the corrected code, and it
should execute without errors.
In [6]: print("Hello, World!") #this code is correct, and it will print "Hello, W
print("Something I'd like to print")
Hello, World!
Something I'd like to print
Comments
In the above example, the texts after hash key # is called comments
Why we need comments?
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Create a single line comment
Comments starts with a #, and Python will ignore them:
In [8]: #This program prints "Hello, World!"
print("Hello, World!")
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of the
line:
[Link] [Link] 2/30
1/14/25, 5:30 PM Python basics
Hello, World!
A comment does not have to be text that explains the code, it can also be used to
prevent Python from executing code:
In [10]: print("Hello, World!")
#print("Cheers, Mate!")
Hello, World!
Hello, World!
Hello, World!
Literal
literals are a notation for representing a fixed value in source code. They can also be
defined as raw value or data given in variables or constants.
Python has different types of literals, such as:
1. Integer literal
78 is an integer literal
2. Floating point literal
23.32 is a floating point literal
3. character literal
'a' is a character literal
4. String literal
"hello" is a string literal
In [13]: x = 78 #78 is integer literal
y = 23.32 #23.32 is floating point literal
z = "a" #"a" is character literal
text = "hello" #string literal
Variable
A variable is just a name to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the computer allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters
in these variables.
print(counter)
print(miles)
print(name)
100
100.23
John
Object References
What is actually happening when you make a variable assignment?
Python is a object-oriented language. In fact, every item of data in a Python program
is an object of a specific type or class (object will be introduced later in this course).
300
When presented with the statement print(300) , the interpreter does the
following:
Creates an integer object
Gives it the value 300
Displays it on the screen
A Python variable is a symbolic name that is a reference or pointer to an object. Once
an object is assigned to a variable, you can refer to the object by that name. But the
data itself is still contained within the object.
For example:
In [27]: n = 300
This assignment creates an integer object with the value 300 and assigns the
variable n to point to that object.
Variable Assignment.
Now consider the following statement:
In [28]: m = n
What happens when it is executed? Python does not create another object. It simply
creates a new symbolic name or reference, m , which points to the same object that
n points to.
Now Python creates a new integer object with the value 400, and m becomes a
reference to it.
Now Python creates a string object with the value "foo" and makes n reference
that.
Orphaned Object.
There is no longer any reference to the integer object 300. It is orphaned, and there
is no way to access it.
Is assignment the same as equality?
No because:
= is assignment operator, x = 15 means we create a variable x and assign
15 to x
== is comparison operator, x == 15 means we compare the value of x with
15. It returns True if x is equal to 15; otherwise, it returns False
[Link] [Link] 6/30
1/14/25, 5:30 PM Python basics
x = 20
print(15 == x)
print(x == 15)
#15 == x is equivalent to x == 15; but 15 = x is different from x = 15
x == 15
15 == x
x=15
True
True
False
False
The following tuple assignment syntax can assign multiple variables in one line.
In [17]: %%optlite --height 200
x, y, z = '15', '30', 15
One can also use chained assignment to set different variables to the same value.
In [21]: %%optlite --height 200
x = y = z = 0
Variables can be deleted using del . Accessing a variable before assignment raises
a Name error.
In [28]: %%optlite --height 400
x = 5
y = 10
del x, y
x, y
Function
A function is a block of code which only runs when it is called.
You can pass data, known as parameters or arguments , into a function.
A function can return data as a result.
print() is a function to print the message on the screen
Arguments
Information can be passed into functions as arguments.
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.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
In [30]: #a function will only be executed when it's called
#In this cell, we only define a function, so it is not executed
def my_function(course_name):
print("Welcome to "+ course_name)
In [31]: my_function("CityU")
Welcome to CityU
To know how to use a built-in function, we can add a question mark before or after
the function name:
In [32]: ?print
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current [Link].
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method
In [33]: print?
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current [Link].
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method
import
Some functions are defined in special libraries and will not be loaded automatically.
We need to import these modules before using the functions.
For example, we can import the math module by typing the following line:
[Link] [Link] 9/30
1/14/25, 5:30 PM Python basics
then, we can use the values and functions defined in the math module
In [35]: print([Link]) #pi is a constant defined in math module
print([Link](1.25)) #sin() is a function defined in math module
3.141592653589793
0.9489846193555862
Identifiers
Identifer is a name to represent various program elements such as variables,
arrays, functions etc.
Identifiers such as variable names are case sensitive and follow certain rules.
a = 10 is different from A = 10
Exercise Evaluate the following cell and check if any of the rules above is violated.
{caution}
For the code to run, you must run the initialization cell
that imports ipywidgets:
````python
from ipywidgets import interact
In [38]: @interact
def identifier_syntax(
assignment=[
"a-number = 15",
"a_number = 15",
"15 = 15",
"_15 = 15",
"del = 15",
"Del = 15",
"type = print",
"print = type",
"input = print",
]
):
exec(assignment)
print("Ok.")
interactive(children=(Dropdown(description='assignment', options=('a-numbe
r = 15', 'a_number = 15', '15 = 15',…
{hint}
- `del` is a keyword and `Del` is not because identifiers
are case sensitive.
- Function names such as `print`, `input`, `type`, etc.,
are not keywords and can be reassigned.
This can useful if you want to modify the default
implementations without changing their source code.
Hello, World!
Hello, World!
{seealso}
To help make their code more readable, programmers follow
additional style guides such as [PEP 8]
([Link]
variable-names):
- Function names should be lowercase, with words separated
by underscores as necessary to improve readability.
- Variable names follow the same convention as function
names.
- good variable names: my_age, my_weight
- bad variable names: xyz, abc123
Out[40]: 15
Out[41]: 15
Out[42]: 15
Out[43]: 15
Out[44]: 107150860718626732094842504906000181056140481170553360744375038837035105
112493612249319837881569585812759467291755314682518714528569231404359845
775746985748039345677748242309854210746050623711418779541821530464749835
819412673987675591655439460770629145711964776865421676604298316526243868
37205668069376
{seealso}
Is there a maximum value for an integer for Python3?
See the [documentation]
([Link]
about `[Link]`.
In the above code, type() is a python function to return the data type of the
inputs.
Run the code below to see how to use type()
In [50]: type?
Property 1 . Python stores a floating point with finite precision, which affects the
check for equality. See the code below.
In [51]: x = 10
y = (x ** (1 / 3)) ** 3
x == y
print(x)
print(y)
10
10.000000000000002
False
True
In [56]: print(sys.float_info.max * 2)
inf
Out[57]: 0.3333333333333333
How to round a floating point number to the desired number of decimal places?
round() function
syntax: round(number, digits)
number -Required. The number to be rounded
digits -Optional. The number of decimals to use when rounding the number.
Default is 0
In [58]: x = 28793.54836
print('round(x)=',round(x)) #round to ones place
print('round(x, 2)=',round(x, 2)) # round to 2 decimal places
print('round(x, 1)=',round(x, 1)) #round to 1 decimal places
print('round(x, 0)=',round(x, 0)) #round to ones place, but return a floa
print('round(x, -1)=',round(x, -1)) #round to tens place
print('round(x, -2)=',round(x, -2)) #round to hundreds place
round(x)= 28794
round(x, 2)= 28793.55
round(x, 1)= 28793.5
round(x, 0)= 28794.0
round(x, -1)= 28790.0
round(x, -2)= 28800.0
Strings
[Link] [Link] 15/30
1/14/25, 5:30 PM Python basics
hello
hello
hello
hello
print(15)
print("15")
print(15+5)
print("15+5")
15
15
20
15+5
We can display a string literal with the print() function. Alternatively, we can assign a
string to a variable, then print the variable
In [65]: print('hello')
s = 'hello'
print(s)
print('hello')
hello = 100
print(hello)
hello
hello
hello
100
Escape sequence
To insert characters that are illegal in a string, we need to use escape
sequence .
\\ Backslash(\)
\n New Line
\t Tab
\b Backspace
print('''I
love
programming''') #we can use triple quotes to enclose multi-line string
7------8
/| /|
3------4 |
| | | |
| 5----|-6
|/ |/
1------2
{seealso}
Pitfall
One common error for beginners is they often mix string up with variable
name
5
hello
Signature: input(prompt='')
Docstring:
Forward raw_input to frontends
Raises
------
StdinNotImplementedError if active frontend doesn't support stdin.
File: /opt/conda/lib/python3.11/site-packages/ipykernel/[Link]
Type: method
Out[74]: '28'
In [72]: x = input()
x
Out[72]: '8'
Hello
Hello, how are you?
the value of x is: 10
Parameters of print()
print(object(s), sep=separator, end=end)
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' (new line)
I love CS1302!
I-love-CS1302!
I*love*CS1302!
In [77]: #by default, the ending character is `\n` which starts a new line
print("I")
print("love")
print("CS1302")
print("I", end='*')
print("love", end='*')
print("CS1302!")
print("I", end='')
print()
print("love", end='')
print()
print("CS1302!")
I
love
CS1302
IloveCS1302!
I*love*CS1302!
I
love
CS1302!
Exercise Explain whether the following code prints 'My name is Python' . Does
print return a value?
Python
My name is None
Please explain why the following python code does not print 'My name is P
print('My name is', print('Python'))
The reason why the code does not print 'My name is Python' as expected i
s due to the way the `print()` function works in Python.
## Corrected Code
To achieve the desired output, you can simply use the `print()` function
with both strings:
```python
print('My name is', 'Python')
```
Alternatively, you can use string concatenation:
```python
print('My name is ' + 'Python')
```
Or, using f-strings (Python 3.6+):
```python
print(f'My name is Python')
```
Answer: print() function returns None. The None keyword is used to define a null
value, or no value at all. It returns a value! It is None.
Type Conversion
[Link] [Link] 21/30
1/14/25, 5:30 PM Python basics
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming.
There are two types of Type Conversion in Python:
Implicit Type Conversion
Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.
Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
In [80]: # Converting integer to float
num_int = 123
num_flo = 1.23
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
print(num_int+num_str)
#example of int()
y_int = int(y)
z_int = int(z)
print(type(y_int))
print(type(z_int))
#example of float()
x_float = float(x)
z_float = float(z)
print(type(x_float))
print(type(z_float))
#example of str()
x_str = str(x)
y_str = str(y)
print(type(x_str))
print(type(y_str))
<class 'int'>
<class 'int'>
<class 'float'>
<class 'float'>
<class 'str'>
<class 'str'>
Note that the input of these functions must be valid, see examples below
In [84]: %%optlite --height 400
x = '123abc'
In [85]: x = '123'
123
123.0
Out[86]: '456'
Out[88]: 15
String Formatting
How to format a string to the desired format?
Syntax: [Link](value1, value2...)
The format() method formats the specified value(s) and insert them inside
the string's placeholder.
The format() method returns the formatted string.
value1, value2... Required. One or more values that should be formatted
and inserted in the string.
Example 1
In [89]: x = 10000/3
print('x ≈',x)
print('x ≈ {:.2f} (rounded to 2 decimal places)'.format(x))
x
x ≈ 3333.3333333333335
x ≈ 3333.33 (rounded to 2 decimal places)
Out[89]: 3333.3333333333335
@interact(
x="10000/3",
align={"None": "", "<": "<", ">": ">", "=": "=", "^": "^"},
sign={"None": "", "+": "+", "-": "-", "SPACE": " "},
width=(0, 20),
grouping={"None": "", "_": "_", ",": ","},
precision=(0, 20),
)
def print_float(x, sign, align, grouping, width=0, precision=2):
format_spec = (
f"{{:{align}{sign}{'' if width==0 else width}{grouping}.{precisio
)
print("Format spec:", format_spec)
print("x ≈", format_spec.format(eval(x)))
Example 2
String formatting is useful for different data types other than float .
E.g., consider the following program that prints a time specified by some variables.
In [91]: # Some specified time
hour = 12
minute = 34
second = 56
The time is 12 : 34 : 56 .
To make the code more readable, we can use the format function as follows.
In [93]: message = "The time is {}:{}:{}."
print([Link](hour, minute, second))
{note}
According to the string formatting syntax, we can change the order of substitution
using
indices (0 is the first item) or
names inside the placeholder {} :
In [94]: print("You should {0} {1} what I say instead of what I {0}.".format("do",
print("The surname of {first} {last} is {last}.".format(first="John", las
Example 3
You can even put variables inside the format specification directly and have a nested
string formatting.
In [95]: align, width = "^", 5
print(f"{{:*{align}{width}}}".format(x)) # note the syntax f"..."
3333.3333333333335
@interact(
expression=r"'ABC'",
fill="*",
align={"None": "", "<": "<", ">": ">", "=": "=", "^": "^"},
width=(0, 20),
)
def print_objectt(expression, fill, align="^", width=10):
format_spec = f"{{:{fill}{align}{'' if width==0 else width}}}"
print("Format spec:", format_spec)
print("Print:", format_spec.format(eval(expression)))
Error
In addition to writing code, a programmer spends significant time in debugging code
that contains errors.
Can an error be automatically detected by the computer?
In [97]: #example of runtime error
x = 5
y = 0
print(x/y)
--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
Cell In[97], line 4
2 x = 5
3 y = 0
----> 4 print(x/y)
You have just seen an example of runtime error, which is due to an error in the
logic.
The ability to debug or even detect such error is, unfortunately, beyond python's
intelligence.
Other kinds of error may be detected automatically.
As an example, note that we can omit + for string concatenation, but we cannot
omit it for integer summation:
In [98]: print('Skipping + for string concatenation')
'4''5' '6'
In [102… %%javascript
let x = '4' * '5' * 6;
[Link](x + ' ' + typeof(x));
// no error because 4 and 5 are converted to numbers implicitly
In [104… try:
!javac [Link]
except Error:
print('Cannot run shell command.')
{note}
- Javascript is [tricky]
([Link]
- To improve readability and avoid logical errors,
[typescript]([Link] is a
strongly-typed replacement of javascript.
Exercise Not all the strings can be converted into integers. Try breaking the following
code by providing invalid inputs and record them in the subsequent cell. Explain
whether the errors are runtime errors.
In [106… num1 = input('Please input an integer: ')
num2 = input('Please input another integer: ')
print(num1, '+', num2, 'is equal to', int(num1) + int(num2))
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[106], line 3
1 num1 = input('Please input an integer: ')
2 num2 = input('Please input another integer: ')
----> 3 print(num1, '+', num2, 'is equal to', int(num1) + int(num2))