Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Python Programming Language

Python is a popular programming language. It was released in 1991.

It is used for:

• web development (server-side),


• software development

What can Python do?

• Python can be used to create web applications.


• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.

Why Python?

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other programming
languages.

Python Syntax compared to other programming languages

• Python was designed for readability, and has some similarities to the English language with influence from
mathematics.
• Python uses new lines to complete a command, as opposed to other programming languages which often
use semicolons or parentheses.

Taking input in Python from the user

• Programs/Softwares often have a need to interact with users, either to get data or to provide some sort of
result. Python provides us with inbuilt functions to read the input from the keyboard.

input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the complete
statement as String. For example, Python provides a built-in function called input which takes the input from
the user. When the input function is called it stops the program and waits for the user’s input. When the user
presses enter, the program resumes and returns what the user typed.
Ex 1 :

name = input('What is your name?\n')


print(name)

Ex 2:
val = input("Enter your value: ")
print(val)

Ex 3:
name = input('What is your name?\n')
print(name)

Ex 4:
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)

How the input function works in Python :

• When input() function executes program flow will be stopped until the user has given input.
• The text or message displayed on the output screen to ask a user to enter an input value, which will be
printed on the screen is optional.
• Whatever you enter as input, the input function converts it into a string.

Python Variables

• a variable is used to store data


• the value in the variable can change
• a variable has a name (identifier)
• Variable names are case sensitive
• you can access data from a variable.

Overall, a variable is a memory location within a program that stores particular values, such as the name, age or
score of a user. The values can change each time the program is run or while the program is running.

Model how to store data in a variable, for example:

Myname = "Jamelia"

Myage = 12
In this case, the variables are called ‘Myname’ and ‘Myage’. Taking the ‘MyName’ variable as an example, discuss
that when the program is run this time, the data stored will be “Jamelia” but that this could change the next time the
program is run.

There are some reserved words that cannot be used. These are words used by the program, for example we cannot
name a variable ‘print’, because this is a command word in Python.

Variables are for storing data values. It is name given to memory location that holds data.

Example:

name = input("What is your name?")

print("Hello ", name)

consider the following questions:

What does the program do?

Answer: It outputs ‘Hello world!’, asks a user to enter their name, then says ‘Hello and name’

What do you think 'print' means?


Answer: It is the instruction to output what is in the brackets

What do you think 'input' means?


Answer: It is the instruction to wait for the text a user enters and to then make use of this

Why is some text in speech marks and some not?

Answer: Speech marks indicate that the exact text will be used when the program is run. No speech marks
means that the content of that memory space is used

What is the purpose of 'name'?

Answer: This is a variable to store the name the user inputs

Creating Variables

Case-Sensitive: Variable names are case-sensitive.


Example: This will create two variables:
a=4
A = "Sally"

Rules for Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Legal/Correct variable names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal/Incorrect variable names:

2myvar = "John"
my-var = "John"
my var = "John"

Output/Displaying result on screen

The Python print() function is often used to output variables and text depending on the requirement of the user.

Example
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".

Python Data Types : Built-in Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types
can do different things.Python has the many data types built-in by default but we will be covering the following:
Python Numbers

There are three numeric types in Python:

• int
• float
• complex

Example

• x = 1 # int
y = 2.8 # float
z = 1j # complex

Integers: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example
x=1
y = 35656222554887711
z = -3255522
Float : Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example

x = 1.10
y = 1.0
z = -35.59

Complex Complex numbers are written with a "j" as the imaginary part:
Example

x = 3+5j
y = 5j
z = -5j

Python Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')
Python Booleans :
Booleans represent one of two values: True or False. In programming you often need to know if an expression
is True or False. You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

Print a message based on whether the condition is True or False:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Note : Most Values are True. Almost any value is evaluated to True if it has some sort of content. Any string is True,
except empty strings. Any number is True, except 0.
Python Operators

Python Operators in general are used to perform operations on values and variables. These are standard symbols used
for the purpose of logical and arithmetic operations. In this article, we will look into different types of Python
operators.
• OPERATORS: Are the special symbols. Eg- + , * , /, etc.

• OPERAND: It is the value on which the operator is applied.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

print(10 + 20)

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

Division (float): divides the first operand by the


/ second x/y

Modulus: returns the remainder when the first


% operand is divided by the second x%y

** Power: Returns first raised to power second x ** y

PRECEDENCE:

• P – Parentheses
• E – Exponentiation
• M – Multiplication (Multiplication and division have the same precedence)
• D – Division
• A – Addition(Addition and subtraction have the same precedence)
• S – Subtraction

Examples of Arithmetic Operator


a = 9
b = 4
add = a + b
sub = a - b
mul = a * b
div1 = a / b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(div1)
print(mod)
Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

# Examples of Assignment Operators

a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Examples of Relational Operators

a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

# Examples of Logical Operator

a = True
b = False
print(a and b)
print(a or b)
print(not a)

Python Conditions and If statements


In Python, condition statements act depending on whether a given condition is true or false. You can execute
different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either
True or False.

There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else
If statement in Python : In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False. If the condition is True, then the True block of code will be executed, and if the
condition is False, then the block of code is skipped

Syntax:

if condition:
statement 1
statement 2
statement n

Example of the if statement. In this example, we will calculate the square of a number if it greater than 5

number = 6
if number > 5:
# Calculate square
print(number * number)
print(“Try again”)

If – else statement

The if-else statement checks the condition and executes the if block of code when the condition is True, and if the
condition is False, it will execute the else block of code.

Syntax of the if-else statement

if condition:
statement 1
else:
statement 2

Example

password = input('Enter password ')

if password == "abc789":
print("Correct password")
else:
print("Incorrect Password")
Chain multiple if statement in Python

In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one after another. This is
useful when you need to check multiple conditions. With the help of if-elif-else we can make a tricky decision.
The elif statement checks multiple conditions one by one and if the condition fulfills, then executes that code.

Syntax of the if-elif-else statement:

if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement

Example

def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")

user_check(1)
user_check(2)
user_check(3)
user_check(4)

Nested if-else statement

In Python, the nested if-else statement is an if statement inside another if-else statement. It is allowed in Python to
put any number of if statements in another if statement.

Indentation is the only way to differentiate the level of nesting. The nested if-else is useful when we want to make a
series of decisions.
Syntax

if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block

Example: Find a greater number between two numbers

num1 = int(input('Enter first number '))


num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
And :

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or:

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

You might also like