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

Simple Syntax

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Simple Syntax

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Python

Python is an example of a high-level language; other high-level languages


you might have heard of are C++, PHP, Pascal, C#, and Java.
The engine that translates and runs Python is called the Python
Interpreter: There are two ways to use it: immediate mode and script
mode. In immediate mode, you type Python expressions into the Python
Interpreter window, and the interpreter immediately shows the result
The >>> is called the Python prompt. The interpreter uses the prompt to
indicate that it is ready for instructions.
You can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script. Scripts have the advantage
that they can be saved to disk, printed, and so on.

Programs
A program is a sequence of instructions that specifies how to perform a
computation. The computation might be something mathematical, such as
solving a system of equations or finding the roots of a polynomial, but it can
also be a symbolic computation, such as searching and replacing text in a
document or (strangely enough) compiling a program.
The details look different in different languages, but a few basic instructions
appear in just about every language:

 input: Get data from the keyboard, a file, or some other device.
 output: Display data on the screen or send data to a file or other
device.
 math: Perform basic mathematical operations like addition and
multiplication.
 conditional execution: Check for certain conditions and execute the
appropriate sequence of statements.
 repetition: Perform some action repeatedly, usually with some
variation.

Python Objects
Each Python object has three defining properties: identity, value, and type.
1. Identity: A unique identifier that describes the object.
2. Value: A value such as "20", "abcdef", or 55.
3. Type: The type of the object, such as integer or string.
The value of an object is the data associated with the object. For example,
evaluating the expression 2 + 2 creates a new object whose value is 4. The
value of an object can generally be examined by printing that object.
The type of an object determines the object's supported behavior. For
example, integers can be added and multiplied, while strings can be
appended with additional text or concatenated together. An object's type
never changes once created. The built-in function type() prints the type of an
object.

Python identifiers
A programmer gives names to various items, such as variables (and also
functions, described later). For example, x = 5 uses the name **x** to refer
to the value 5. A name, also called an identifier, is a sequence of letters (a-z,
A-Z, _) and digits (0-9). An identifier must start with a letter. Note that "_",
called an underscore, is considered to be a letter.
Upper and lower case letters differ. That is, Python is case sensitive,
so cat and Cat are different.
 The following are valid names: c, cat, Cat, n1m1,
short1, and _hello.
 The following are invalid names: 42c (doesn't start with a letter), hi
there (has a space), and cat$ (has a symbol other than a letter or
digit).
Names that start and end with double underscores (for example, __init__) are
allowed but should be avoided, because Python has special use for double
underscore names.
A good variable name should describe the purpose of the variable, such as
"temperature" or "age", rather than just "t" or "A".
A good practice when naming variables is to use all lowercase letters and to
place underscores between words (e.g., "last_name", "birth_place").
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Thus, Age and age are two different identifiers in Python.

Reserved Words
Reserved words are keywords for which Python has specific purposes. These
are words that you cannot use as variable, function, or any other identifier
names. All the Python keywords contain lowercase letters only. Many
language editors will automatically color a program's reserved words.
The following list shows the Python keywords. These are python
keywords:

keyboard_arrow_down

Statements
A statement is an instruction that the Python interpreter can execute.
When you type a statement on the command line, Python executes it.

keyboard_arrow_down

Output
print("Hello World!")

[]
print("Hello World")
account_circle
Hello World!

[]
print("hello world")
account_circle
hello world

[]
print('Hello World')
account_circle
Hello World

[]
print("Anything you write in between the quotes is a string, and you can print it")
account_circle
Anything you write in between the quotes is a string, and you can print it
[]
print("Anything you write in between the "" is a string, and you can print it")
account_circle
Anything you write in between the is a string, and you can print it

[]
print("Anything you write in between the \" is a string, and you can print it")
account_circle
Anything you write in between the " is a string, and you can print it

[]
print("Anything you write in between the \"\" is a string, and you can print it")
account_circle
Anything you write in between the "" is a string, and you can print it

keyboard_arrow_down

Comments
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
# This is your first comment

print("Hello, Python!") # second comment

This produces the following result:


Hello, Python!
You can type a comment on the same line after a statement or expression:
name = "Jane Smith" # This is again a comment

[]
# This is your first comment
# see how this Colab interpreter colors comments in green?
# other interpreters may color them differently (e.g., in gray)
# also, when you execute the code, all the comments are ignored

print("Hello, Python!") # inline comment


account_circle
Hello, Python!

keyboard_arrow_down

Variables
Variables are nothing but reserved memory locations 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 interpreter 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.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space.
The declaration happens automatically when you assign a value to a
variable. The equal sign = is used to assign values to variables. A common
error among new programmers is to assume = means equals, as in
mathematics. In contrast, = means "compute the value on the right, and
then assign that value to the variable on the left."
The operand to the left of the = operator is the name of the variable and
the operand to the right of the = operator is the value stored in the
variable.
# operand operator operand
# variable assignment_operator value

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name, respectively.

[]
Name = "John Smith"
name = "Jane Doe"

a = 2+3
print(a)

print(Name + " is different from " + name + str(a))


account_circle
5
John Smith is different from Jane Doe5

Variable names are case sensitive. In this example,the variable Name is


different from the variable name.
Variables are not permanently assigned to objects. A variable can be
reassigned to another object, and multiple variables can refer to the same
object.
[]
age = 10
print(age)

age = 11
print(age)

age = 12
print(age)
account_circle
10
11
12

keyboard_arrow_down

Standard Data Types


The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for
each of them.
Python has five standard data types
 Numeric
 String
 Boolean
 List
 Tuple
 Dictionary
To verify the type of any object in Python, use the type() function

Numeric data types


Python supports four different numerical types
 int (signed integers)
 long (long integers, they can also be represented in octal and
hexadecimal)
 float (floating point real values)
 complex (complex numbers)
Variables of numeric types are created when you assign a value to them:
int_var = 35
float_var = 3.5
complex_var = 1j

Integers (signed integers)


Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
var1 = 35679945
var2 = 28
var3 = -29576

Floating point numbers


A floating-point literal is written with the fractional part even if that fraction
is 0, as in 1.0, 0.0, or 99.0
Float type objects have a limited range of values that can be represented.
For a standard 32-bit installation of Python, the maximum floating point
value is approximately 1.8x10308, and the minimum floating point value is
2.3x10-308. Assigning a floating point value outside of this range generates
an OverflowError. Overflow occurs when a value is too large to be stored in
the memory allocated by the interpreter. For example, the below program
tries to store the value 2.01024, which causes an overflow error.
Integers vs Floating Point literals
In general, floating-point types should be used to represent quantities that
are measured, such as distances, temperatures, volumes, weights, etc.,
whereas integer types should be used to represent quantities that are
counted, such as numbers of cars, students, cities, hours, minutes, etc.
When doing floating-point calculations, the programmer should be aware of
the difference between integer and floating-point literals.
500 will be represented as an integer in memory (e.g., using an int type),
whereas 500.0 will be represented as a floating-point number (using a float
type).

[]
a = 500 # this will be represented as an integer in memory
print(a)
print(type(a))

b = 500.0 # this will be represented as a floating point number


print(b)
print(type(b))
c = "500.0" # this will be represented as a string
print(c)
print(type(c))
account_circle
500
<class 'int'>
500.0
<class 'float'>
500.0
<class 'str'>

keyboard_arrow_down

String data types


Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and ends the
string.
The triple quotes are used to span the string across multiple lines. For
example, all the following are legal −

[]
variable_word = 'word'
print(variable_word)

sentence = "This is a sentence."


print(sentence)

paragraph = """This is a paragraph. It is


made up of multiple lines and sentences."""
print(paragraph)
account_circle
word
This is a sentence.
This is a paragraph. It is
made up of multiple lines and sentences.

keyboard_arrow_down

Boolean data types


[]
true = True
print(true)
print(type(true))
false = False
print(false)
print(type(false))
account_circle
True
<class 'bool'>
False
<class 'bool'>

[]
while False:
print("hello world")

print("nothing happened")

keyboard_arrow_down

Data type Conversion


Sometimes, you may need to perform conversions between the built-in
types. To convert between types, you simply use the type name as a
function.
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
 Type complex(x, y) to convert x and y to a complex number with real
part x and imaginary part y. x and y are numeric expressions
 Type str(x) to conver x to a string
These functions return a new object representing the converted value.

[]
x = 50
print(x)
print(type(x))

y = float(x)
print(y)
print(type(y))
z = str(y)
print(z)
print(type(z))

keyboard_arrow_down

Input
Let's see another function. Input receives something from the standard
input, in this case your keyboard, and it assigns it to a variable. By default
the received input is a string.
a = input()

If you pass an argument inside of the parenthesis, it is displayed as text in


the screen right before the input prompt
a = input("Enter some text")

[]
a = input()
print(type(a))
print(a)
account_circle
4.7
<class 'str'>
4.7

[]
a = input("Enter some text ")
print(type(a))
print(a)
account_circle
Enter some text enter some text
<class 'str'>
enter some text

[]
a = input("Enter a number ")
print(type(a))
print(a)
account_circle
Enter a number 6
<class 'str'>
6

[]
a = int(input("Enter a number "))
print(type(a))
print(a)
account_circle

[]
a = float(input("Enter a number "))
print(type(a))
print(a)

[]
a = complex(input("Enter a complex number "))
print(type(a))
print(a)
account_circle
Enter a complex number 6
<class 'complex'>
(6+0j)

arrow_upwardarrow_downward
link
settings
delete
more_vert
[]
max_number = max(3,6)
min_number = min(5,7)
print("this is the max number: ",str(max_number))
print(min_number)
a = 45
a = my_function()
account_circle
this is the max number: 6

You might also like