1 Python Basics

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18
At a glance
Powered by AI
Python is a popular, high-level programming language used by many organizations like Google, NASA, and Disney. It can be used for web programming, scripting, scientific computing, and artificial intelligence.

Python is used for web programming, scripting, scientific computing, and artificial intelligence. It is very popular and used by organizations such as Google, NASA, the CIA, and Disney.

Floats represent numbers that aren't integers (whole numbers) and are created using a decimal point or division. They are stored approximately rather than perfectly.

Python

SoloLearn
Welcome to Python!
Python is a high-level programming language, with applications in
numerous areas, including web programming, scripting, scientific
computing, and artificial intelligence.

It is very popular and used by organizations such as Google, NASA, the


CIA, and Disney.

In this course we will be learning Python version 3, which is the most


recent major version of Python.
Your First Program
• Let's start off by creating a short program that displays "Hello world!".
In Python, we use the print statement to output text.
Tap Try It Yourself and see it in action: print('Hello world!')

Congratulations! You have written your first program.

The print statement needs to be followed by parentheses, which


enclose the output we want to generate.
Run, save and share your Python code on our Code Playground
without installing any additional software.
Simple Operations
Python has the capability of carrying out calculations. Enter a calculation directly into the print statement:
print(2 + 2)
print(5 + 4 - 3)

The spaces around the plus and minus signs here are optional (the code would work without them), but
they make it easier to read.
Python also carries out multiplication and division, using an asterisk * to indicate multiplication and a
forward slash / to indicate division. Use parentheses to determine which operations are performed first.
print( 2 * (3 + 4) )
print( 10 / 2 )
Using a single slash to divide numbers produces a decimal (or float, as it is called in programming). We'll
have more about floats in a later lesson.
• Dividing by zero in Python produces an error, as no answer can be
calculated.print(11 / 0)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

In Python, the last line of an error message indicates the error's type.
Read error messages carefully, as they often tell you how to fix a
program!
Floats
Floats are used in Python to represent numbers that aren't integers (whole numbers). Some examples
of numbers that are represented as floats are 0.5 and -7.8237591. They can be created directly by
entering a number with a decimal point, or by using operations such as division on integers.
print( 3/4 )
As you saw previously, dividing any two integers produces a float.
A float is also produced by running an operation on two floats, or on a float and an integer.print( 8 / 2 )

print( 6 * 7.0 )
print( 4 + 1.65 )
A float can be added to an integer, because Python silently converts the integer to a float.

Computers can't store floats perfectly accurately, in the same way that we can't write down the
complete decimal expansion of 1/3 (0.3333333333333333...). Keep this in mind, because it often leads
to infuriating bugs!
Exponentiation
Besides addition, subtraction, multiplication, and division, Python also
supports exponentiation, which is the raising of one number to the
power of another. This operation is performed using two asterisks.
print( 2**5 )
print( 9 ** (1/2) )

You can chain exponentiations together. In other words, you can rise a
number to multiple powers. For example, 2**3**2.
Quotient
Floor division is done using two forward slashes and is used to
determine the quotient of a division (the quantity produced by the
division of two numbers).

For example:
print( 20 // 6 )

The code above will output 3, because 6 goes into 20 three times.
You can also use floor division on floats.
Remainder
The modulo operator is carried out with a percent symbol (%) and is
used to get the remainder of a division.

For example:
print(20 % 6)
print(1.25 % 0.5)

All numerical operators can also be used with floats.


Strings
If you want to use text in Python, you have to use a string. A string is created by entering text between two single or
double quotation marks.
print("Python is fun!")
print('Always look on the bright side of life')
The delimiter (“(double quotation) or ‘(single Quotation)) used for a string doesn't affect how it behaves in any way.
Backslash
Some characters can't be directly included in a string. For instance, double quotes can't be directly included in a
double quote string; this would cause it to end prematurely.

Characters like these must be escaped by placing a backslash before them. Double quotes only need to be escaped
in double quote strings, and the same is true for single quote strings.

For Example: print(‘Ravan\'s mother: He\'s not an angel. He\'s a very dangerous!')

Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can't be
reliably printed.
Newlines

\n represents a new line. It can be used in strings to create multi-line output:


print('One \nTwo \nThree

Newlines will be automatically added for strings that are created using three
quotes.
print("""this
is a
multiline
text""")

Similarly, \t represents a tab.


String Operations
Concatenation
As with integers and floats, strings in Python can be added, using a process called concatenation, which can be done
on any two strings.
print("Spam" + 'eggs')
When concatenating strings, it doesn't matter whether they've been created with single or double quotes. Even if
your strings contain numbers, they are still added as strings rather than integers.
print("2" + "2")

Adding a string to a number produces an error, as even though they might look similar, they are two different
entities.
Multiplication
Strings can also be multiplied by integers. This produces a repeated version of the original string. The order of the
string and the integer doesn't matter, but the string usually comes first.
print("spam" * 3)
print(4 * '2')

Strings can't be multiplied by other strings. Strings also can't be multiplied by floats, even if the floats are whole
numbers.
Variables
A variable allows you to store a value by assigning it to a name, which can be used to refer to the value later in
the program. For example, in game development, you would use a variable to store the points of the player.

To assign a variable, use one equals sign.


user = “Info1"
x=7
print(x)
print(x + 3)
print(x)
Variables can be reassigned as many times as you want, in order to change their value. In Python, variables
don't have specific types, so you can assign a string to a variable, and later assign an integer to the same
variable.
x = 123.456
print(x)
x = "This is a string"
print(x + "!")

However, it is not good practice. To avoid mistakes, try to avoid overwriting the same variable with different
data types.
Variable Names
Certain restrictions apply in regard to the characters that may be used in Python variable names. The only characters
that are allowed are letters, numbers, and underscores. Also, they can't start with numbers. Not following these rules
results in errors.
this_is_a_normal_name = 7

123abc = 7 # SyntaxError: invalid syntax


Python is a case sensitive programming language. Thus, Lastname and lastname are two different variable names in
Python.

You can use the del statement to remove a variable, which means the reference from the name to the value is deleted,
and trying to use the variable causes an error.
temp = 3
del temp
print(temp)

Deleted variables can be reassigned to later as normal.


temp = 2
temp2 = 3
del temp2
temp2 = 8
print(temp * temp2)
User Input
• To get input from the user in Python, you can use the intuitively named input function. For example, a game can ask for the user's
name and age as input and use them in the game.
The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).
x = input()
print(x)

• Even if the user enters a number as input, it is processed as a string.The input statement needs to be followed by parentheses.
You can provide a string to input() between the parentheses, producing a prompt message. For example:
name = input("Enter your name: ")
print("Hello, " + name)

• The prompt message helps to clarify what input the program is asking for. Let's assume we want to take the age of the user as
input. We know that the input() function returns a string. To convert it to a number, we can use the int() function or You can
convert to float using the float() function. :
age = int(input())
print(age)

• Similarly, in order to convert a number to a string, the str() function is used. This can be useful if you need to use a number in
string concatenation. For example:
age = 42
print("His age is " + str(age))
In-Place Operators
In-place operators allow you to write code like 'x = x + 3' more concisely, as 'x += 3'.
The same thing is possible with other operators such as -, *, / and % as well.
x=2
print(x)
x += 3
print(x)
These operators can be used on types other than numbers, as well, such as strings.
x = "spam"
print(x)
x += "eggs"
print(x)

In-place operators can be used for any numerical operation (+, -, *, /, %, **, //).
• Which of these will not be stored as a float?
• 2/4
• 7.0
7
• Fill in the blank with the output of this code. print(1 + 2 + 3 + 4.0 + 5)
• Answer : 15.0
• What is the result of this code? print( 7%(5 // 2) )
• 0
1
• 7
• Which of the following options results in exactly two lines?
• "Some \n text \n goes here"
• "Hello world"
• 'one \' two \' three'
"Hello \n world"
• Which line of code produces an error?
• "7" + 'eight'
'5' + 6
• 3+4
• "one" + "2"
• What is the output of this code?

spam = "7"
spam = spam + "0"
eggs = int(spam) + 3
print(float(eggs))
• 10.0
 73.0
• 703
• What is the output of this code?

word = "cheese"
print(word + ' shop')
 cheese shop
• Error
• cheeseshop
• What is the output of this code?

x=5
y=x+3
y = int(str(y) + "2")
print(y)
Answer ‘82’

You might also like