Python Intro - New
Python Intro - New
System Programming
Graphical User Interface Programming (PyQt5 is the
most popular option for creating graphical apps with
Python.)
Database Programming
Game development
Why do people use Python….. ?
The following primary factors cited by Python users seem to be these:
Python is object-oriented(concepts of classes, abstraction,
etc.) with very simple syntax rules.
It’s free (open source) that is available for everyone to
use.
Because of its human-friendly syntax, it's easy to write,
read, and debug
It’s powerful
It’s portable(works on variety of platforms – Windows,
linux, Mac).
Its completeness(need not to install additional libraries).
Installing Python
https://www.python.org/downloads/
- Download the latest version of python IDLE and install, recent
version is 3.12.0
Running Python
Relational operators:
>>> print (2 < 3 ) True
>>> print (2 != 3) True
>>> print (False < True ) True
Variable In Python
What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
Python Variable Types
Every value in Python has a datatype. Different data types in Python are
Numbers, List, Tuple, Strings, Dictionary, set, etc. Variables in Python can be
declared by any name or even alphabets like a, aa, abc, etc.
Variable
Create a Variable:
>>> x = 10
>>> x
10
Assigning a new value:
>>> x = 20
>>> x
20
Multiple assignments
Variable Definition
In Python, a variable is created when you first assign a value to it. It also means
that a variable is not created until some value is assigned to it.
Example:
print(x)
x=20
print(x)
When you run the above code, it will produce an error for the first statement only –
name ‘x’ is not defined.
So, to correct the above code-
x=0 #variable x created now
print(x)
x=20
print(x)
** A variable is defined only when you assign some value to it. Using an undefined
variable in an expression/statement causes an error called Name Error.
Dynamic Typing
A variable pointing to a value of a certain type, can be made to point
to a value/object of different type. This is called Dynamic Typing.
Example:
x = 10
We can say that variable x is referring to a value of integer type.
Later in your program, if you reassign a value of some other type to
variable x, Python will not raise any error, i.e.,
x =10
print(x)
x=‘Hello World’
print(x)
Caution with Dynamic Typing
Although Python is comfortable with changing types of a variable, the
programmer is responsible for ensuring right types for certain type of operations.
For example,
Python String Concatenation
and Variable
x+=y x= x+y
x - =y x=x-y
x *=y x=x*y
x/=y x=x/y
x//=y x=x//y
x**=y x=x**y
Examples:
f=‘god’, g=‘God’, h=‘god’, j=‘God’, k=“Godhouse”
f==h will return True
“God”==“Godhouse” will return True
g== j will return True
“god” < “Godhouse” will return False (based on ASCII value of g &
G)
• Dictionary
• Set
Numbers
Number data types are used to store numeric values in Python. The numbers in
Python have following core data types:
a) Integers - are whole numbers such as 5,39,1917,0 etc. They have no
fractional parts. Integers can be positive or negative.
b) Booleans – represent the truth values False and True. False and True behave
like the values 0 and 1, respectively. To get the Boolean equivalent of 0 or 1,
you can type bool(0) and bool(1), Python will return False or True
respectively.
String: Data Type
Strings:
Output:
indexing syntax without step: elcome to sc
indexing syntax with step: ecm os
Slicing with positive and negative index
s = "Welcome to scaler"
s1 = s[3 : -7]
print("positive start index, negative end index:", s1)
# above slice operation can also be written as
s2 = s[-14 : 10]
print("negative start index, positive end index:", s2)
Output:
Output:
('a', 'b')
Membership operators
‘in’ and ‘not in’ are membership operators.
‘in’ – returns true if a character/substring exists in a given string.
‘not in’ – returns true if a character/substring does not exist in the
given string.
Syntax: <substring> in <string>
<substring> not in <string>
Built in String Methods:
len() – returns the length of the string.
Syntax: len(str)
capitalize() – first letter is in uppercase
Syntax: str.capitalize()
split() – breaks up a string at the specified separator and returns a list of
substrings.
Syntax : str.split( [ separator [, maxsplit ] ] )
** Note : a) If separator is not specified, any white space string is a
separator.
b) Default value of maxsplit is 0.
c) split into n+1 strings.
** if we wish to display the output on the next line, then the use of escape
sequence ‘\n’ becomes mandatory.
We can also use escape sequence (\t) to tabulate the output.
Multiline Strings
Traversing a String
Means accessing all the elements of the string one after the other by
using the subscript or index value.
Strings are immutable
You cannot change the values. That means, strings in Python are
immutable.
So, still if you want to change the value, you can do one thing:
Write a Python program to print all the words in an input string.
Write a Python program to remove the words beginning with vowels.
Write a program in Python to count lower, upper, numeric and special
characters in a string.
Basic Practice Questions:
1. Write a Python program to check if the given number is greater than 5. If
the number is greater than 5, then print the cube of the number. If the
number is less than or equal to 5, then print the square of the number.
2. Write a program to check whether the given two numbers are same or not.
If they are same, then check if the first number is greater than second
number.
3. Write a program to count the number of digits in any number.
Type() function
If we wish to determine the type of a variable i.e., what type of value
does it hold/point to, then type() function is used.
Input() function
It is used to get data from the user while working with the script mode. It is
used us to accept an input string from the user without evaluating its value.
Input() function always accepts input in the form strings and hence
manipulates number as strings only and does not generate the desired
result.
So, we use another function int().
Int() function converts the inputted string into numeric values and
shall store the value 30 as a number and not as string. Thus , we will
obtain the desired output as 70(sum of 30 and 40).
Decision Making
Decision-making statements are used to control the flow of execution
of program depending upon condition.
There are four types of decision-making statements in Python:
a) if statement
b) if-else statement
c) if-elif ladder
d) Nested if-else statement
If statement
Syntax:
if condition:
statement(s)
If-else statement
Syntax:
If condition:
statement(s)
else:
statement(s)
If-elif-else statement
Syntax:
If condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Nested If-else statement
Syntax:
If condition:
statement(s)
if condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Practice Questions
Write a python program to check the profit or loss
Write a program to check whether the given character is an uppercase letter or
lowercase letter
Write a program to check whether or not a given number is less than 50. if the
number is less than 50, then check if the number is greater than 25 or not. If the
number is less than 25, then check whether the number is even or odd.
Named Conditions:
The traditional way of writing code will be :
if deposit < 2000 and time >=2:
rate = 0.05
But if you name the conditions separately and use them later in your code, it adds
to readability and understandability of your code, e.g.,
eligible_for_5_percent = deposit < 2000 and time >=2
eligible_for_7_percent = 2000 <= deposit < 6000 and time >=2
Now you can use these named conditions in the code as follows:
if eligible_for_5_percent:
rate = 0.05
elif eligible_for_7_percent:
rate = 0.075
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Ques1. Write a program to calculate BMI (body mass index) of a person.
Body mass index is a simple calculation using a person’s height and
weight.
The formula is BMI = kg/m2 where kg is person’s weight and m2 is their
height in metres squared.
Ques3. Write a program that reads two numbers and an arithmetic operator
and displays the computed result.
Ques4. Write a program to print whether a given character is an uppercase
or a lowercase character or a digit or any other character.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
Comparison operators
Comparison operators are used to compare values. It returns either True or False
according to the condition.
Logical operators
Logical operators are the and, or, not operators.
Bitwise Operators
Bitwise operators are like logical operators but they work on individual bits.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)