0% found this document useful (0 votes)
6 views15 pages

Chapter 1 ( Intro to Python

The document provides an introduction to Python programming, emphasizing its ease of learning and the basic concepts of programming logic. It covers essential topics such as expressions, data types, variables, and the use of an Integrated Development Environment (IDE) for writing Python code. Additionally, it includes a simple example program to illustrate how to interact with users and perform basic operations.

Uploaded by

uzairznkhattak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views15 pages

Chapter 1 ( Intro to Python

The document provides an introduction to Python programming, emphasizing its ease of learning and the basic concepts of programming logic. It covers essential topics such as expressions, data types, variables, and the use of an Integrated Development Environment (IDE) for writing Python code. Additionally, it includes a simple example program to illustrate how to interact with users and perform basic operations.

Uploaded by

uzairznkhattak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

So what we studied in our previous lessons about python: lets recall them:

Why python?

Its easy to start with to jump in programming languages, and to learn the
other languages of computer science, you just need to know the logics of
programming languages, and most of the languages use the same logics. So
python makes it easier to learn about those logics. While if you start from
other languages, like traditionally from C or C++, its usually makes
understanding the logics complicated making the student, demotivational in
learning the programming languages.

Programming is simply the act of entering instructions for the computer to


perform. These instructions might crunch some numbers, modify text, look
up information in files, or communicate with other computers over the
internet.

All programs use basic instructions as building blocks. Here are few of
the most common ones, in English:

 Do this, then do that


 If this condition is true, perform this action; otherwise do that action
 Do this action exactly 27 times
 Keep doing that until this condition is true.

You can combine these building blocks to implement more intricate


decisions too, for example, here are the programming instructions called
the source code, for a simple program written in python programming
language. Starting at the top, the python software runs each line of code (
some lines are run only if certain condition is true or else python runs
some other lines ) until it reaches the bottom.
Another thing is that, its not necessary for a programmer to be a Math God,
or to know math. Yeah basic arthametic functions are basic necessity but you
don’t have to be like that Chiniese guy in the class.

Programming is a creative activity, like painting, writing, knitting, or


constructing Lego castles. Like painting a blank canvas, making software has
many constraints but endless possibilities.

The difference between the programming and other creative activities


is that when programming, you have all the raw materials you need in your
computer; You don’t need to buy any additional canvas, paint, film, yarn,
Lego bricks, or other electronic components, A decade old computer is more
than powerful enough to write programs. Once your program is written, it
can be copied perfectly an infinite number of times. A knit sweater can only
be worn by one person at a time but a useful program can easily be shared
online with the entire world.

You write programming languages in a text editor ( called IDE) there are
many types of IDE, Like Spyder, Anaconda, or the most common, the Visual
Studio code, but these are too complex for a beginner to start with, so to
make it easier, we will gonna start with Mu editor, its one easy IDE for
Python, where the interface looks calm and easier. It is also supported on
Linux, Windows and Mac so availability isn’t a problem

IDE is for us to write or edit the code called Source Code, but its still is raw.
And computer don’t understand just source code, we all know that Computer
Only understands Binary Numbers. So for that , we use an interpreter or
compiler , that actually converts our code into Binary code so then our
machine, or computer understands it.

Python programming language has a wide range of syntactical


constructions, standard library functions , interactive development
environment features, Fortunately you can ignore most of thatl you just need
to learn enough to write some handy little programs.

Expressions: in python, 2 + 2 is called expressions, which is the most


basics kind of programming instruction in the language. Expressions consist
of values ( such as 2) and operators ( such as + ), and they can always
evaluate ( that is reduce ) down to a single value. That means you can use
expressions anywhere in python code that you could also use a value.

You can use plenty of other operators in Python expressions, too. For
example, Table below lists all the math operators in Python

The order of operations (also called precedence) of Python math


operators is similar to that of mathematics. 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. Whitespace in
between the operators and values doesn’t matter for Python (except for the
indentation at the beginning of the line), but a single space is convention.

In each case, you as the programmer must enter the expression, but
Python does the hard part of evaluating it down to a single value. Python will
keep evaluating parts of the expression until it becomes a single value, as
shown here
Then we have Integers, Floating-Point and string data types:

Integers: -2 , -1 , 0 , 1 , 2 , 3

Floating-Point Numbers: -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25

Strings: ‘a’ , ‘aa’ , ‘aaa’ , ‘Hello!’ , ’11 cats’

String Concatenation and Replication:

String concatenation means that adding up two strings, its like ‘Alice’ +
‘Adams’ reduces down to ‘AliceAdams’ and String Replication means
Replicating a string like ‘Alice’ * 5 making it to ‘AliceAliceAliceAliceAlice’

Its to understand that although operators work great with the integers and
floating point numbers, but not all work well with strings, the only 2 operator
works with the strings are addition operator and multiplication operator with
specific rules. Like you can either add two strings or you can replicate a
string by multiplying it with an integer.

Variables:

Variables are like a box in computer’s memory, you assign or make variables
to store some values in it, it can be Boolean value, or String, or integer, or
Floating points.

Either you can store value while writing a code or you can just create an
empty variable and let the user to store any value in it, its like letting the
user to create a username, it will remain in the variable ( username = input()
for ever.

Assignment statements:
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, then a variable named spam will have the integer
value 42 stored in it.

Think of a variable as a labeled box, that a value is placed in, as in Fig


below:

Variables values can be updated, once you create a variable and input a
value , then create the variable again with the same name, and give a
different value, The value will change and new value will replace the older
value. Its called value over writing

There are some rules before creating a variable:

 It can be only one word with no spaces.


 It can use only letters, numbers, and the underscore (_) character.
 It cant begin with a number.
Your First Program:

We write our python programs in your File editor, the file editor is similar to
the text editors such as notepad or textmate, but it has some features
specifically for entering source code.

The file editor lets you type in many instructions, save the file, and run
the program. Here’s how you can tell the difference between the two:

 The interactive shell window will always be the one with the prompt
>>>.
 The file editor window will not have the prompt >>>.

Now its time to create your first program! When the file editor window opens,
Enter 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()

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.')


Once you entered your source code, save it so that you wont have to retype
it each time you start Mu. Click the Save button, Enter hello.py File Name
Field, and then click Save.

Press the F5 key to run the program. The program output in the
interactive shell should look something like this:

Hello, world!

What is your name?

Uzair

It is good to meet you, Uzair

The length of your name is:

What is your age?

21

You will be 22 in a year.

When there are no more lines of code to execute, the python program
terminates; That is, it stops running. ( You can also say that Python program
exits.)

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. Your previously saved Hello.py program should open in the file editor
window.

Dissecting Your Program:

With your new program open in the file editor, Lets take quick tour of
the python instructions it uses by looking at what each line of code does.

Comments:

The following line is called a comment.


#This program says hello and asks for my name.

Python ignores comments and you can use them to write notes or
remind your self what the code is trying to do. Any text for the rest of the line
following a hash mark (#) is part of a comment.

Sometimes, programmers will put a # in front of a line of code to


temporarily remove it while testing a program. This is calling commenting
out code. And it can be useful when you are trying to figure out why a
program isn’t working. You can remove the # later when you are ready to put
the line back in.

Python also ignores the blank line after the comment. You can add as
many blank lines to your program as you want.This can make your code
easier to read like a paragraph in a book.

The print() Function:

The print() function displays the string values inside its parentheses on the
screen.

print('Hello, world!')

print('What is your name?') # ask for their name

The line print(‘Hello World’) means “Print out the text in the string
‘Hello World!’”. When python executes this line, you say that python is
calling the print() function and the string value is being passed to the
function. A value that is passed to a function is called an argument. Notice
that the quotes are not printed to the screen. They just mark where the
string begins and ends; They are not part of the string value.

Note : You can also use this function to put a blank line on the screen; just
call print() with nothing in between the parentheses.

When you write a function name, the opening and closing parentheses
at the end identify it as the name of a function. We will learn more about
functions after the chapter of Flow control
The input() Function

The input function waits for the user to type sometext on the keyboard
and press Enter.

myName = input()

This function call evaluates to a string equal to the user’s text, and the
line of code assigns the myName variable to this string value.

You can think of the input() function call as an expression that


evaluates to whatever the string the user typed in, if the user entered ‘Uzair’,
Then the expression would evaluate to myName = ‘Uzair’.

Printing the user’s name

The following call to print() actually contains the expression 'It is good
to meet you, ' + myName between the parentheses.

print('It is good to meet you, ' + myName)

Remember that expressions can always evaluate to a single value. If


‘Uzair’ is the value stored in myName variable. Then this expression
evaluates to ‘It is good to meet you, Uzair’. This single string value is then
passed to print(), Which prints it on the screen.

Len() Function

You can pass the len() function a string value ( or a variable evaluates
to the integer value of the number of characters containing a string ) and the
function in that string.

print('The length of your name is:')

print(len(myName))

Enter the following into the interactiveshell to try this:

>>> len('hello')

>>> len('My very energetic monster just scarfed nachos.')

46

>>> len('')
0

Just like those examples, len(myName) evaluates to an integer. It is


then passed to print() to be displayed on the screen. The print() function
allows you to pass it either integer value or string value, but notice the error
that shows up when you type the following into the interactive shell:

>>> 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 only concatenate str (not "int") to str

The print() function isn’t causing that error, but rather it’s the expression you
tried to pass to print(). You get the same error message if you type the
expression into the interactive shell on its own.

>>> 'I am ' + 29 + ' years old.'

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

'I am ' + 29 + ' years old.'

TypeError: can only concatenate str (not "int") to str

Python gives an error because the + operator can only be used to add two
integers together or concatenate two strings. You cant 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, as explained in the next section.

The str(), int(), and float() Functions.

If you want to concatenate and integer such as 29 with a string to pass to


print(), you’ll need to get the value ‘29’, which is a string form of 29. The
str() function can be passed an integer value and will evaluate to a string
value version of the integer, as follows:

>>> str(29)

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

I am 29 years old.

Because str(29) evaluates to ’29’, the expression 'I am ' + str(29) + '
years old.', Which in turn evaluates to 'I am 29 years old’. This is the value
that is passed to the print() function.

The str(), int(), and float() functinos will evaluate to the string, integer,
and floating-point forms of the value you pass, respectively. Try converting
some values in the interactive shell with these functions and watch what
happens.

>>> str(0)

'0'

>>> str(-3.14)

'-3.14'

>>> int('42')

42

>>> int('-99')-99

>>> int(1.25)

>>> int(1.99)

>>> float('3.14')

3.14

>>> float(10)

10.0

The previous examples call the str() , int() , and float() functions and
pass them values of the other data types to obtain a string, integer, or
floating-point form of those values.
The str() function is handy when you have an integer or float that you
want to concatenate to a string. The int() function is also helpful if you have
a number as a string value that you want to use in some mathematics. For
example, the input() function always returns a string, even if the user enters
a number. Enter spam = input() into the interactive shell and enter 101
when it waits for your text.

>>> 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

Now you should be able to treat the spam variable as an integer


instead of a string.

>>> spam * 10/5

202.0

Note that if you pass a value to int() that it cannot evaluate as an


integer, python will display an error message.

>>> int('99.99')

Traceback (most recent call last):

File "<pyshell#18>", line 1, in <module>

int('99.99')

ValueError: invalid literal for int() with base 10: '99.99'

>>> int('twelve')

Traceback (most recent call last):


File "<pyshell#19>", line 1, in <module>

int('twelve')

ValueError: invalid literal for int() with base 10: 'twelve'

The int() function is also useful if you need to round a floating-point


number down.

>>> int(7.7)

>>>int(7.7)+1

You used the int() and str() functions in the last three lines of your
program to get a value of the appropriate data types 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 myAge variable contains the value returned from the input().
Because the input() function always returns a string ( even if the user typed
in a number ), you can use the int(myAge) code to return an integer value of
the string in myAge. This integer value is then added to 1 in the expression
int(myAge) + 1.

The result of this addition is passed to the str() function: str(int(myAge)


+ 1). The string value returned is then concatenated with the strings 'You will
be ' and ' in a year.' To evaluate to one large string value. This large string is
finally passed to print() to be displayed on the screen.

Lets say the user enters the string ‘4’ for myAge. The string ‘4’ is
converted to an integer, so you can add one to it. The result is 5. The str()
function coverts the result back to a string, so you can concatenate it with
the second string,’ in a year.’, so create the final message. These evaluation
steps would look something like the following:

Summary

You can compute expressions with a calculator or enter string


concatenation with a word processor. You can even do string replication
easily by copy and pasting texts. But expressions and there component
values, operators, variables, and functions calls--- are the basic building
block sthat make programs. Once you know how to handle these elements,
you will be able to instruct Python to operate on large amounts of data for
you.

Its good to remember the different types of operators ( +,-,*,/,//,%,


and ** for math operations, and + and * for string operations ) and the three
data types ( integers, floating-point numbers, and strings ) introduced in this
chapter.
We introduced a few different functions as well. The print() and input()
functions handle simple text output ( to the screen ) and input ( from the
keyboard ). The len() functions takes a string and evaluates to an int of the
number of the characters in the string. The str(), int() and float() functions
will evaluate to the string, integer, or floating-point number form of the value
they are passed.

In next chapter, you’ll learn how to tell python to make intelligent


decisions about what code to run, what code to skip and what code to repeat
based on the values it has. This is known as flow control, and it allows you to
write program that make intelligent decisions.

You might also like