date: 2024-02-19
title: Python Basic
author:
- AllenYGY
status: DONE
tags:
- NOTE
- Python
- Program
created: 2024-02-19T16:28
updated: 2024-05-31T01:23
publish: True
Python Basic
The following assignments of variables are all valid.
a = 1.2
a = "Daisy"
a, b = "Hello", "World"
# a is "Hello" and b is "World"
a = b = [1,2,3]
# a and b are both [1,2,3]
Python has a smaller set of keywords than C does.
All the python keywords, as shown below, contain only lowercase letters.
and, exec, not, as, finally, or, assert,
for, pass, break, from, print, class, global,
raise, continue, if, return, def, import, try,
del, in, while, elif, is, with, else,
lambda, yield, except
In Python, end of a statement is marked by a newline character (no semicolon!). But we can write a single statement over multiple lines with the line continuation character (\). For example:
# use "\" to divide one statement over multiple lines
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
Further, line continuation is implied inside parentheses (()), brackets ([]) and braces ({}). In the following example, the line continuation character can be omitted.
print("Hello",
"World")
gender = ["female",
"male"]
If you want to put multiple statements in a single line, seperate them using semicolons (;).
a = 1; b = 2; c = 3
Python does not use braces ({}) to indicate blocks of code. Code blocks are denoted by line indentation and this is rigidly enforced. Wrong indentation will cause error!
A code block starts with indentation and ends with the first unindented line.
Generally four whitespaces are used for indentation. In a Jupyter notebook, you may press "tab" to input four whitespaces.
Till now, we have used the print()
function for output for plenty of times. For input, we have the input()
function, and its syntax is:
input([prompt])
prompt
is a string which can be printed on the screen. This parameter is optional. Below is an example.
name = input("What is your name? ")
print(name, "is a good name :)")