0% found this document useful (0 votes)
5 views36 pages

Python Basic Syntax and Variables

This document provides an overview of basic Python syntax, including comments, indentation, variables, data types, and control flow structures like if statements. It covers essential concepts such as variable naming conventions, numeric expressions, string manipulation, and the use of input and print functions. Additionally, it explains boolean operators and decision-making in Python programming.

Uploaded by

lmzantout
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views36 pages

Python Basic Syntax and Variables

This document provides an overview of basic Python syntax, including comments, indentation, variables, data types, and control flow structures like if statements. It covers essential concepts such as variable naming conventions, numeric expressions, string manipulation, and the use of input and print functions. Additionally, it explains boolean operators and decision-making in Python programming.

Uploaded by

lmzantout
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Lecture 4: Python Basic Syntax

Python code – General guidelines


# This program to add two numbers
• Write one instruction per line x=1
y=2

Comments
z=x+y #add x and y
print(z)

Serve the purpose of offering explanations to the source code reader


regarding the actions taking place within a specific code block where
the comment is placed. When the code is executed, the interpreter
disregards comments. A single-line comment is initiated with the
pound sign (#).
if True:
• Indentation print("This is the if block.")
print("It is indented.")
else:
It is of utmost importance as it indicates blocks of coded
print("This is the else block.")
(more on that later) print("It is also indented.")

print("This is outside the if-else block.")


Print Function
Round brackets

print("Hello", "world")

Function name
Arguments
>>>print("Hello", "World!") >>>print("Hello" + "World!")
Hello World! HelloWorld!
>>>print("Hello") >>>print("Hello" + " " + "World!")
print("World!") Hello World!
Hello
World!
It display Hello World! on different lines.
Variables
Variables are defined and assigned whenever needed
The assignment is using the = sign
• Variables are automatically assigned a type when an assignment
operation is done:
• num = 2 is an integer (int)
• dec = 2.1 is a decimal (float)
• sentence = "How are you?" is a string
b = True is a boolean (bool)

Be consistent in naming convention (snake_case) and use meaningful


variables to improve readability.
Variables Naming Conventions

Every variable should start with a letter or underscore, that can be


followed by any series of letters, digits, or underscores.
You cannot use reserved words as variable names / identifiers.

>>> grade1 = 10 >>> $temp=40


>>> grade2 = 20 SyntaxError: invalid syntax
>>> y_access= 1.5 >>> if=40
>>> temp = 40 SyntaxError: invalid syntax
>>> 2temp = 40
SyntaxError: invalid syntax
If is a reserved word
Variables

Variables in python are case-sensitive to letter case.


'myVariable' and 'myvariable' are seen as different variables.

>>> low = 10
>>> Low = 5.7
>>> print(low)
10
>>> print(Low)
5.7
>>> print(LOW)
NameError: name 'LOW' is not defined
Numeric Expressions
• The type int is for integer numbers Operator Operation
• You can perform the classical arithmetic operations (addition, + Addition
subtraction and multiplication) on integers and floats: +, -, *
- Subtraction
• Regarding division, there are two types:
Decimal division which syntax is /, the result is a float * Multiplication
• Integer division which syntax is //, the result is the quotient which is / Float Division
an integer
// Integer Division
>>> x = 5 >>> print(x**y) >>> print(x/y) ** Power
>>> y = 2 25 2.5
% Remainder
>>> z= 4 >>> print(x%y) >>> print(z/y)
>>> print(x - y) 1 2.0 2 2
3 >>> print(z%y) >>> print(x//y) 2 5 2 4
>>> print(x*y) 0 2 4 4
10 1 0
Remainder Remainder
Numeric Expressions - Floats

• The type float is for floating-point >>> print(2 + 3.4)


numbers (decimal) 5.4
>>> print( 2 + 3)
• An operation between a float and an
5
integer returns a float
>>> print(5/2 * 2 + 1)
• To convert a variable myVar into a 6.0
float, use the keyword >>> print(5//2 * 2 + 1)
float(myVar)
5
• To convert a variable into an integer,
use the keyword int(myVar)
Operator Precedence Rules

Precedence rules in Python are similar to


math.
1 + 6 / 2 * 2 ** 3
Parentheses

1+6/2*8
Exponent

Multiplication, Division, and Remainder


1 + 3.0 * 8

Addition and Subtraction


1 + 24.0

Left to right
25.0
Datatype Conversion

We have several types of conversions between strings, integers and


floats using the built-in int, float, and str functions

>>> x = 12 >>> y = "34" >>> y = "34.3" >>> z = 41.8


>>> float(x) >>> float(y) >>> float(y) >>> int(z)
12.0 34.0 34.3 41
>>> str(x) >>> int(y) >>> int(y) >>> str(z)
'12' 34 Error '41.8'
Input function
function name One argument

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


output is saved in a variable

By default, in Python, the input


function reads the user's input >>> number = input("Enter an integer: ")
as a string. Enter an integer: 3
>>> number
'3'

A string!

How can we ensure that an input number is stored as a numeric value rather than a string?
Input Function -Datatype Conversion

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

We can convert the string output of the input function into an integer
using the built-in int function
>>> number = int(input("Enter an integer: "))
Enter an integer : 3
>>> number
3

An integer
(not a string)!
Input Function -Datatype Conversion

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


We can convert the string output of the input function into a float using
the built-in float function
>>> number = float(input("Enter a float: "))
Enter a float: 3
>>> number
3.0

A float
(not a string)!
More about Print Function
Python f-Strings simplify the process of printing values and
variables.
>>> name='ahmad'
>>> course='INFS1101’

>>> print(f"Hi {name}, a warm welcome to the {course}


class!")
Hi ahmad, a warm welcome to the INFS1101 class!

This is code.
Indicated by curly
brackets.

In Python, the code inside an f-string is executed before it's printed.


Variable types - String
• A string is a list of characters, where each character is a
>>> s1 = "Hello"
letter, a digit or other symbols
>>> s2 = "World"
• Strings are defined using double quote, e.g.: >>> s3 = s1 + s2
• greeting = "Hello" >>> s3
• subject = "everyone" 'HelloWorld'
>>> s4 = s1 + ' ' + s2
• Operations on strings are different from arithmetic
>>> s4
operations
'Hello World'
• One basic operation on strings is concatenation: >>> s5 = s1 * 3
• greeting + subject >>> s5
'HelloHelloHello'
Repetition builds a string by multiple concatenations of a
string with itself
greeting * 2
String length
• The number of characters in a string is called the string length
• greeting = "Hello"
• In this example the length of "Hello" is 5.
• To programmatically obtain the length of a string use the len function:
len("Hello") has the value 5.
Indexing Strings

The characters of a string can be accessed individually by using


squared brackets and the position, starting from 0

H E L L O

0 1 2 3 4
>>> greeting = "HELLO"
>>> greeting[4] Index does not exist
'O'
>>> greeting[0]
'H'
>>> greeting[5]
IndexError: string index out of range
Indexing Strings

We can also index a string from the right end using a negative number.

-5 -4 -3 -2 -1
H E L L O

0 1 2 3 4

>>> greeting = "HELLO"


>>> greeting[-1]
'O'
>>> greeting[-5]
'H'
Substring

It is also possible to extract a substring by specifying the position of the


first character and the position after the last character to be extracted
separated by a colon.

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9 10
>>> greeting = "HELLO WORLD" >>> greeting[:7]
>>> greeting[0:5] 'HELLO W' Assume zero as the
'HELLO' >>> greeting[:] default if start is not
>>> greeting[1:5] 'HELLO WORLD' specified
'ELLO' >>> greeting[12:1]
>>> greeting[6:12] ‘’-When the start index is greater than the end index, Python returns an
'WORLD' empty string.
String case conversion
• Strings also have useful functions for case conversions
• upper() converts a string to uppercase
[Link]() refers to "HELLO"
• lower() converts a string to lowercase
[Link]() refers to "hello"
capitalize() converts the first letter of the string to uppercase
[Link]() refers to "Hello"

>>> [Link]()
upper() does not modify the
Remember: This function operates on 'HELLO'
string in place, it returns a
the value stored within the variable, not >>> greeting
new string.
the variable's name itself. 'Hello'
Decision in Python
FALSE
• Simple if statement Condition

TRUE
if (condition) :
instruction1_inside_the_if

instruction1_inside_the_if
instruction2_inside_the_if instruction1_inside_the_if

instruction_outside_the_if

instruction_outside_the_if
START

Decision in Python age=int(input("How old


are you? "))

• Simple if statement – example:


FALSE
Age>=18
age=int(input("How old are you? "))
if (age >= 18) :
TRUE
double = age * 2
Double = age * 2
print("In " + str(age) + " years you will be " +
str(double))
print("Have a nice day!") print("In " + str(age) +
" years you will be " +
str(double))

What is the output if age=20? What is the output if age=16?

print("Have a nice
In 20 years you will be 40 Have a nice day! day!")

Have a nice day!

END
Decision in Python
FALSE
condition
• If else statement
TRUE

if (condition) : instruction1_inside_the_else instruction1_inside_the_if

instruction1_inside_the_if
instruction2_inside_the_if instruction2_inside_the_if
instruction2_inside_the_else
else :
instruction1_inside_the_else
instruction2_inside_the_else
instruction_outside_the_if
instruction_outside_the_if
Decision in Python START

age=int(input("How old
are you? "))
• If else statement – example:
age=int(input("How old are you? "))
if (age >= 18) : FALSE
Age>=18
double = age * 2
print("In " + str(age) + " years you will be " +
str(double)) TRUE
else :
remaining = 18 - age double= age*2
remaining = 18 - age
print("In " + str(remaining) + " years you will be 18!")
print("In " + print("In " + str(age) +
print("Have a nice day!") str(remaining) + " " years you will be " +
years you will be str(double))
18!")
What is the output if age=20? What is the output if age=16?

In 20 years you will be 40 In 2 years you will be 18!


print("Have a nice
Have a nice day! Have a nice day! day!")

END
Decision in Python
FALSE condition
1
• If elif else statement
TRUE
if (condition1) : FALSE condition
2
instruction1_inside_the_first_if
instruction1_inside_the_first_if
TRUE
instruction2_inside_the_first_if
instruction2_inside_the_first_if
elif (condition2) : Instruction1_inside_second if

instruction1_inside_the_else
instruction1_inside_the_second_i
f
Instruction2_inside_second if

instruction2_inside_the_second_i instruction2_inside_the_else
f
else :
instruction1_inside_the_else
instruction2_inside_the_else
instruction_outside_the_if
instruction_outside_the_if
Decision in Python • What is the output if age=20?

• If elif else statement – example: In 20 years you will be 40


Have a nice day!

age=int(input("How old are you? "))


if (age >= 18) :
double = age * 2 • What is the output if age=16?
print("In " + str(age) + " years you will be " +
str(double)) In 2 years you will be 18!
elif (age >= 12) : Have a nice day!
remaining = 18 - age
print("In " + str(remaining) + " years you will be 18!")
else :
• What is the output if age=5?
print("You are too young…")
print("Have a nice day!")
You are too young…
Have a nice day!
When using if … elif … else, Python checks the conditions one by one, from top to
bottom. As soon as it finds a condition that is True, it runs that block and skips the rest.
That’s why with age=20, even though both conditions (age > 18 and age > 12) are true,
only the first block runs.
Decision in Python • What is the output if age=20?
In 20 years you will be 40
• If if else In -2 years you will be 18!
Have a nice day!
age=int(input("How old are you? "))
if (age >= 18) :
double = age * 2
print("In " + str(age) + " years you will be " + • What is the output if age=16?
str(double))
if (age >= 12) : In 2 years you will be 18!
remaining = 18 – age Have a nice day!
print("In " + str(remaining) + " years you will be 18!")
else :
print("You are too young…")
print("Have a nice day!") • What is the output if age=5?

You are too young…


Have a nice day!

Note that in the first case (20) both conditions are true (age > 18, age >12) and both blocks are executed.
Boolean Operator Precedence Rules

Boolean operators in Python help you make decisions with True and
False. 'and' needs both to be True, 'or' needs at least one, and 'not'
flips them around.
Not True or True and
Parentheses True or True and False False

False or True and False


Not True or False

False or False
And
True

Or
False

Left to right
Boolean Operator Examples

T T
True
T F
False

F T
True
F F
False
T T
True
Comparisons Operators - Examples

2<6 True Less than

2 != 6 True Not equal to

2 == 6 False Equal to (Notice double ==)

2 >= 6 False Greater than or equal to

1<2<6 True
Multiple comparisons.
2 is greater than 1 and 2 is less than 6

Single '=' is assignment


Double '==' is comparison
Practice your understanding of printing:
totalGrades = 190
name="ahmad"
print ("Hello " + [Link]() + ", your total is " + str(totalGrades) + " and your average =" + str(totalGrades//3) + ".")

output:
Hello Ahmad, your total is 190 and your average =63.

print ("Hello" , [Link]() , ", your total is " , totalGrades , " and your average =" , totalGrades//3 , ".")

output:
Hello Ahmad , your total is 190 and your average = 63 .

print ("Hello" , [Link]() + ", your total is" , totalGrades , "and your average =" , totalGrades//3, ".")

output:
Observe
how we
Hello Ahmad, your total is 190 and your average = 63 .
removed
this print (f"Hello {[Link]()}, your total is {totalGrades} and your average ={totalGrades//3}.")
space.
output:
Hello Ahmad, your total is 190 and your average =63.
Practice
Write a program that prompt the user to enter a number and print "positive" if number is
greater than 0, otherwise print "negative".
Sample run 1:
Enter an integer:10
START
10 is positive
Input
num num = int(input("Enter an integer:"))
Sample run 2: if num > 0:
Enter an integer:-5 print(num, "is positive")
FALSE
num>0 else:
-5 is negative print(num, "is negative")

TRUE

Output Num Output Num


"is negative" " is Positive"

END
Practice
Write a program that prompt the user to enter a number and print "positive" if number is greater than 0, if
the number if less than 0 print "negative", otherwise print "Zero".
Sample run 1:
START num = int(input("Enter an integer:"))
Enter an integer:10 if num > 0:
Input
10 is positive print(num, "is positive")
num
elif num < 0:
print(num, "is negative")
Sample run 2: FALSE FALSE else:
Enter an integer:-5 num<0 num> 0 print("It is zero")

-5 is negative TRUE TRUE


Output Num
Output Num "is
Sample run 3: negative"
"is positive"

Enter an integer:0
It is zero
Output
"It is zero"
END
>>> 2x = 1 >>> x = 5
SyntaxError: invalid syntax >>> print(int(x))
>>> x = 1 >>> %x = 1 5
Practice
>>> print(type(x)) SyntaxError: invalid syntax >>> print(float(x))
5.0
<class 'int'> >>> law = 1 >>> print(str(x))
>>> x = 1.5 >>> Law = 2 5
>>> print(type(x)) >>> print(law) x = 5.5
<class 'float'> 1 >>> print(int(x))
>>> x = '12' >>> print(Law) 5
>>> print(type(x)) 2 >>>x = '5.5'
<class 'str'> >>> print(LAW) >>> print(float(x))
>>> x = True NameError: name 'LAW' is not defined 5.5
>>> print(type(x)) >>> x = 4 >>>x = '5.5'
>>> print(int(x))
<class 'bool'> >>> y = 5*x + 2
ValueError: invalid literal for int()
>>> x = False >>> print(y) >>> x = '12'
>>> print(type(x)) 22 >>> print(int(x))
<class 'bool'> >>> y = 5*x + 2.0 12
>>> x = 'True' >>> print(y) >>> print(float(x))
>>> print(type(x)) 22.0 12.0
<class 'str'> >>> x = 5 >>> print(str(x))
>>> print(x/2) 12
>>> print(type(input("Enter age")))
>>> x = "hi"
<class 'str'> 2.5
>>> print(x*3)
>>> print(type(int(input("Enter age")))) >>> print(x//2) hihihi
<class 'int'> 2
>>> x = '12.5' >>> print(2+3) >>> print(x[-5])
Practice
>>> print(int(x)) 5 h
ValueError: invalid literal for >>> print("2+3") >>> print(x[1:3])
int() with base 10: '12.5' 2+3 el
>>> print(float(x)) >>> x = 'hello' >>> print(x[0:3]) #first 3 letters
12.5 >>> y="ahmad" hel
>>> print(str(x)) >>> print(x + y) >>> print(x[0:2]) #first 2 letters
12.5 helloahmad he
>>> print(bool(100)) >>> print(x + " " + y) >>> print(x[-3:]) #last three letters
True hello ahmad llo
>>> print(bool(-1)) >>> print(x + 1) >>> print(x[-2:]) #last two letters
True TypeError: can only concatenate str (not "int") to str Lo
>>> print(bool(0)) >>> print(x[0]) >>> x = 2
False h >>> print(x*x*x) #Equivelant x to power 3
>>> print([Link]()) >>> print(x[4]) 8
HELLO o >>> print(x**3) #x to power 3
>>> print([Link]()) >>> print(x[5]) 8
hello IndexError: string index out of range >>> print(x%2) #remainder of x divided by 2
>>> print([Link]()) >>> print(x[-1]) 0
Hello o >>> x=5
>>> len(x) >>> print(x[-5:-1]) >>> print(x%2) #remainder of x divided by 2
5 hell 1
>>> s1='Hi'
>>> s2='INFS1101' a = 50 a = 50
>>> print (s1 , "class", s2) b = 50 b = 50
Practice
Hi class INFS1101 if b >= a: if b >= a:
>>> print (s1 + " class "+ s2) n=1 n=1
Hi class INFS1101 if a == b: elif a == b:
>>> print (f"{s1} class {s2}") n=2 n=2
Hi class INFS1101 if b < a: elif b < a:
>>> s="You grade is" n=3 n=3
>>> grade = 90 print(n) print(n)
>>> print (s + grade) print("have a nice day!") print("have a nice day!")
TypeError: can only concatenate str
(not "int") to str a = 60 a = 50
>>> print (s + " " + str(grade)) b = 50 b = 50
You grade is 90 if b > a: if b >= a:
>>> if 'U' in 'UDST': n=1 print(1)
print(1) elif a == b: if a == b:
1 n=2 print(2)
>>> if True: else: if b < a:
print(1) n=3 print(3)
1 print(n) print("have a nice day!")
>>> if False: print("have a nice day!")
print (1)
Nothing will be printed

You might also like