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

Chapter1_PythonBasics

Uploaded by

Kavitha Palani
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)
15 views

Chapter1_PythonBasics

Uploaded by

Kavitha Palani
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
You are on page 1/ 37

MODULE 1

1. Python Basics
2. Flow control
3. Functions
CHAPTER 1

Python Basics
Python Basics

■ The Python programming language has a wide range of scope


■ Standard library functions
■ Interactive
■ Development environment features.
Entering expressions into the
interactive Shell

■ You run the interactive shell by launching IDLE


■ A window with the >>> prompt should appear; that’s the interactive shell. Enter 2 +
2 at the prompt to have Python do some simple math.
>>> 2 + 2
4
In Python, 2 + 2 is called an expression,
It is the most basic kind of programming instruction in the language. Expressions
consist of
1. values (such as 2)
2. operators (such as +),
And they can always evaluate (that is, reduce) down to a single value.
Entering expressions into the
interactive Shell
■ A single value with no operators is also considered an expression,
though it evaluates only to itself, as shown below
>>> 2
2
Entering expressions into the
interactive Shell
Precedence

■ The order of operations (also called precedence)


■ The ** operator is evaluated first; the *, /, //, and % operators are
evaluated next, from left to right; and the + and - operators are
evaluated last (also from left to right). You can use parentheses to
override the usual precedence if you need to
■ 5*2+1
Example
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>>2+ 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
Evaluating Expression
Syntax Error

>>> 5 +
File "<stdin>", line 1
5+
^
SyntaxError: invalid syntax
>>> 42 + 5 + * 2
File "<stdin>", line 1 42 + 5 + * 2
^
SyntaxError: invalid syntax
>>> 'Hello world!
SyntaxError: EOL while scanning string literal
>>> a=2
type(a)
The integer, floating-Point, and String
data types

■ Expressions are just values combined with operators, and they always
evaluate down to a single value. A data type is a category for values,
and every value belongs to exactly one data type.
String concatenation and
replication
■ The meaning of an operator may change based on the data types of the values next to it.
■ For example, + is the addition operator when it operates on two integers or floating-point
values.
■ >>>2+2
■ 4

■ However, when + is used on two string values, it joins the strings as the string concatenation
operator. Enter the fol- lowing into the interactive shell:
■ >>> 'Alice' + 'Bob’
■ >>>”Ashwini”+”D”
■ “AshwiniD”
■ 'AliceBob'
String concatenation and
replication
■ if you try to use the + operator on a string and an integer value, Python
will not know how to handle this, and it will display an error message.
■ >>> 'Alice’ + 42
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module> 'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly
The error message Can't convert 'int' object to str implicitly means that
Python thought you were trying to concatenate an integer to the string
'Alice'. Your code will have to explicitly convert the integer to a string,
because Python cannot do this automatically.
String concatenation and
replication
■ The * operator is used for multiplication when it operates on two integer
or floating-point values. But when the * operator is used on one string
value and one integer value; it becomes the string replication operator.
■ 3*3
■ >>> 'Alice’ * 5
■ 'AliceAliceAliceAliceAlice’
■ The expression evaluates down to a single string value that repeats the
original a number of times equal to the integer value.
■ String replication is a useful trick, but it’s not used as often as string
concatenation.
String concatenation and
replication
■ The * operator can be used with only two numeric values (for
multiplication) or one string value and one integer value (for string
replication). Otherwise, Python will just display an error message.
■ >>> 'Alice' * 'Bob'
Traceback (most recent call last):
■ File "<pyshell#32>", line 1, in <module> 'Alice' * 'Bob' TypeError:
can't multiply sequence by non-int of type 'str' >>> 'Alice' * 5.0
Traceback (most recent call last):
■ File "<pyshell#33>", line 1, in <module> 'Alice' * 5.0 TypeError: can't
multiply sequence by non-int of type 'float'
Storing Values variable in Variables

■ A variable is like a box in


the computer’s memory
where you can store a
single value. If you want to
use the result of an
evaluated expression later
in your program, you can
save it inside a variable.
■ A=2*2
■ Print(A)
■ 4
Assignment Statement

■ You’ll store values in variables with an assignment


statement. An assignment
■ statement consists of a variable name, an equal sign
(called the assignment
■ operator), and the value to be stored. If you enter the
assignment statement
■ spam = 42, a variable named spam will have the integer
value 42 stored in it.
Example

>>> spam = 40
>>> spam
40
>>> eggs = 2
>>> spam + eggs
42
>>> spam + eggs + spam
82
>>> spam = spam + 2
>>> spam
42
Assignment
Statements with
string

>>> spam = 'Hello’


>>> spam
'Hello'
>>> spam = 'Goodbye’
>>> spam
'Goodbye'
Variable Names

■ You can name a variable anything as long as it obeys the following


three rules:
■ It can be only one word.
■ It can use only letters, numbers, and the underscore (_) character.
■ It can’t begin with a number.
Variable Names

■ Variable names are case-sensitive, meaning that spam, SPAM, Spam,


and sPaM are four different variables. It is a Python convention to start
your variables with a lowercase letter.
■ Spam=4
■ spam=5
■ A good variable name describes the data it contains.
your first Program
■ open the file editor in IDLE, select File->New Window.
■ Now it’s time to create your first program! When the file
editor window opens, type the following into it:
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
myName = input() #Ashwini
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
select File->Save As
Select Run->Run Module
Output
General Instruction

■ You can close the file editor by clicking the X at the top of the window.
To reload a saved program, select File->Open from the menu. Do
that now, and in the window that appears, choose hello.py, and click
the Open button.
■ You can close the file editor by clicking the X at the top of the window.
To reload a saved program, select File4Open from the menu. Do that
now, and in the window that appears, choose hello.py, and click the
Open button. Your previously saved hello.py program should open in
the file editor window.
■ Your previously saved hello.py program should open in the file editor
window.
Dissecting your Program

■ Comments
# This program says hello and asks for my name.
The print() Function
print('Hello world!')
print('What is your name?') # ask for their name
■ The input() Function
■ The input() function waits for the user to type some text on the keyboard
and press enter.
■ myName = input()
Dissecting your Program

■ Printing the User’s Name


■ print('It is good to meet you, ' + myName)
■ The len() Function
■ print('The length of your name is:’)
■ print(len(myName))
■ >>> len('hello’)
5
■ >>> len('My very energetic monster just scarfed nachos.’)
■ 46
>>> len('')
0
Dissecting your Program

■ >>> print('I am ‘ + 29 + ' years old.’)


Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module> print('I am ' + 29 + ' years old.')
TypeError: Can't convert 'int' object to str implicitly
■ Python gives an error because you can use the + operator only to add
two integers together or concatenate two strings. You can’t add an
integer to a string because this is ungrammatical in Python. You can
fix this by using a string version of the integer instead
The str(), int(), and float()
Functions
>>> str(29)
'29'
>>> print('I am ‘ + str(29)+ ' years old.’)
I am 29 years old.
>>> str(0)
'0'
>>> str(-3.14)
'-3.14’
>>> int('-99’)
-99
>>> int(1.25)
1
>>> int(1.99)
The str(), int(), and float()
Functions
>>> spam = input()
101
>>> spam
'101'
■ The value stored inside spam isn’t the integer 101 but the string '101'. If
you want to do math using the value in spam, use the int() function to
get the integer form of spam and then store this as the new value in
spam.
■ >>> spam = int(spam)
■ >>> spam
101
The str(), int(), and float()
Functions
■ >>> spam * 10 / 5
202.0
Note that if you pass a value to int() that it cannot evaluate as an inte-
ger, Python will display an error message.
The int() function is also useful if you need to round a floating-point
number down.
>>> int(7.7)
7
>>> int(7.7) + 1 8
25
The str(), int(), and float()
Functions
■ In your program, you used the int() and str() functions in the last three
lines to get a value of the appropriate data type for the code.
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
The str(), int(), and float()
Functions
Alternative Using f-
strings
■ print(f’ You will be {int(myAge) + 1} in a year.')
The f before the string in Python 3.6+ is used to create an f-string (formatted
string literal). It allows you to embed expressions inside curly brackets {}
within a string.
The f before the string makes it an f-string.An f-string allows us to insert
variables or expressions inside {} directly in a string.This removes the need for
string concatenation (+) or .format().
Questions
1. Which of the following are operators, and which are values?
*
'hello’
-88.8
-
/
+
5
2. What should the following two expressions evaluate to?
■ 'spam' + 'spamspam'
■ 'spam' * 3
3. Why does this expression cause an error? How can you fix it?
■ 'I have eaten ' + 99 + ' burritos.'
Answer
1. operators *, -,/,+ and values ‘hello’, -88.8, 5
2. 'spam' + 'spamspam'
'spamspamspam'
3. print('I have eaten ' + str(99) + 'burritos.’)
or
print(f'I have eaten {99} burritos.')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy