Python Variables
Variable Assignments:
Rules:
Names can't star with a number, can't contain spaces (you could use _ instead), and any of these below special characters:
:'",<>/?|\!@#%^&*~-+
It's a best practice to use lower case
Don't use Python built-in keywords like str, list, and set
Assigning values:
you assignment operator "equal sign = "
Syntax: name =object
Example: a = 10
Determining variable type with type()
Using python built-in type() function you can check what type of object is assigned to a given variable.
List of data types:
int, float, list, str, tuple, set, dict, bool
Examples:
>>> type(a)
<class 'int'>
>>> b=12.5
>>> type(b)
<class 'float'>
>>> c=(1,2)
>>> type(c)
<class 'tuple'>
>>> d=[1,2]
>>> type(d)
<class 'list'>
>>> e='feroz'
>>> type(e)
<class 'str'>
>>> f={1,2}
>>> type(f)
<class 'set'>
>>> g={"fruit":"apple","drink":"coffee"}
>>> type(g)
<class 'dict'>
>>> a= 10 > 9
>>> type(a)
<class 'bool'>
Strings:
In Python strings are used to record text information, such as names.
Define String:
banner = 'hello' or "hello"
Example:
>>> banner="hello"
>>> print(banner)
hello
Define Phrase:
>>> banner='hello World'
>>> print(banner)
hello World
Define quotes:
banner = 'I'am leaving home' ---- This will give error because the single quote in I'm will stop the string
>>> banner='I'm leaving home'
File "<stdin>", line 1
banner='I'm leaving home'
^
SyntaxError: invalid syntax
To avoid the error you should use double quote " to complete the sentence
>>> banner="I'm leaving home"
>>> print(banner)
I'm leaving home
Length function:
You can use built-in len() function to check the length of a string
>>> len("Hello")
5
>>> len("Hello World!")
12
Note: Spaces and punctuation are calculated as string so value is 12 for the above example
String Indexing:
Strings are a sequence, so Python can use indexes to call parts of sequences.
Use [] to call its index, and every indexing starts at 0.
>>> s="Hello World"
>>> s[0]
'H'
>>> s[1]
'e'
>>> s[6]
'W'
String Slicing:
Use : to perform slicing
>>> s="Hello World"
>>> s[::] ----------------- print everything
'Hello World'
>>> s[1:] -------------- print from first index
'ello World'
>>> s[2:]
'llo World'
>>> s[0:]
'Hello World'
>>> s="Hello World"
>>> s[:1] ------------- Print up to the first index
'H'
>>> s[:2]
'He'
>>> s[:5] ------------- Print up to the fifth index
'Hello'
Note: In Python, where statements and are usually in the context of "up to, but not including".
>>> s[:-1]
'Hello Worl' ------ Print everything except last letter
Index and Slicing:
You can use index and slicing notation to grab elements of a sequence by a defined step size and default step size is 1
>>> s[::1] -------- print everything
'Hello World'
>>> s[::] ---------- print everything (by default step size is 1)
'Hello World'
>>> s="Hello World"
>>> s[::2] ---------- print everything but go in step size of 2
'HloWrd'
>>> s="Hello World"
>>> s[::-1] ------ print everything but in reverse order
'dlroW olleH'
String concatenation:
Use concatenation + to add two strings
>>> first_name=" Feroz "
>>> last_name=" Mohammed "
>>> full_name=first_name+last_name
>>> print(full_name)
Feroz Mohammed
String Multiplication:
Use multiplication symbol to reptation of word
>>> letter='Z'
>>> letter * 15
'ZZZZZZZZZZZZZZZ'
Build-in String methods:
We call methods with a period and then the method name.
Syntax: object.method(parameters)
The list of available build-in methods are:
s.capitalize( s.expandtabs( s.isalpha( s.isnumeric( s.ljust( s.removesuffix( s.rsplit( s.swapcase(
s.casefold( s.find( s.isascii( s.isprintable( s.lower( s.replace( s.rstrip( s.title(
s.center( s.format( s.isdecimal( s.isspace( s.lstrip( s.rfind( s.split( s.translate(
s.count( s.format_map( s.isdigit( s.istitle( s.maketrans( s.rindex( s.splitlines( s.upper(
s.encode( s.index( s.isidentifier( s.isupper( s.partition( s.rjust( s.startswith( s.zfill(
s.endswith( s.isalnum( s.islower( s.join( s.removeprefix( s.rpartition( s.strip(
Example:
>>> s="hello world"
>>> s.upper()
'HELLO WORLD'
>>> s.lower()
'hello world'
>>> s.capitalize()
'Hello world'
String Formatting:
String formatting lets you inject items into a string without using string concatenation.
There are different ways to perform string formatting:
- The old method involves placeholders using the modulo % character.
- An improved technique uses the .format() string method.
- The new method, introduced with Python 3.6, uses formatted string literals, called f-strings.
Formatting with placeholders:
% is used to as a "string formatting operator" and %s is used to inject strings into the print statement.
Example:
>>> print ("I'll be visiting university %s in the morning." %'tomorrow')
I'll be visiting university tomorrow in the morning.
You can define multiple values by placing them inside a tuple within commas after the % operator
Example:
>>> print ("I'll be visiting university %s in the %s." %('tomorrow', 'morning'))
I'll be visiting university tomorrow in the morning.
You can also achieve by defining variable names:
Example:
>>> t='tomorrow'
>>> m='morning'
>>> print("I'll be visiting university %s in the %s." %(t, m))
I'll be visiting university tomorrow in the morning.
Format conversion method
The two methods %s and %r convert any python object to a string.
%s ---- str() called as string
%r ---- repr() called as representation
Example:
>>> print("My name is %s." %('feroz'))
My name is feroz.
>>> print("My name is %r." %('feroz'))
My name is 'feroz'. ---- the print statement has 'feroz' quoted with string '' so it denotes it's a type string
Padding and Precision of Floating Point Numbers:
Floating point numbers use the below format
%number of characters the string should contain. numbers to show past the decimal point f
Example:
%6.3f
Where 6 would be the minimum number of characters the string should contain, and if the entire number doesn't have this many digits (like 6 ) then it may be padded with whitespace.
.3f stands for how many numbers to print after the decimal point.
Example:
>>> print('The taxed amount of this month: %6.3f' %(29.65789))
The taxed amount of this month: 29.658
>>> print('The taxed amount of this month: %5.2f' %(29.65789))
The taxed amount of this month: 29.66
>>> print('The taxed amount of this month: %6.4f' %(29.65789))
The taxed amount of this month: 29.6579
>>> print('The taxed amount of this month: %6.5f' %(29.65789))
The taxed amount of this month: 29.65789
>>> print('The taxed amount of this month: %6.6f' %(29.65789))
The taxed amount of this month: 29.657890 ------- we want to printed 6 digits after the decimal but there is no, so it added 0 at the end to print 6 digits
>>> print('The taxed amount of this month: %6.7f' %(29.65789))
The taxed amount of this month: 29.6578900
>>> print('The taxed amount of this month: %15.2f' %(29.65789))
The taxed amount of this month: 29.66 ----- padded with whitespace since the number is not large to 15 digits (we use to print 12 digits)
Multiple Formatting:
You can use multiple formatting method in one go: I have use %s, %r and %2.3f (floating point numbers)
>>> print('I have paid taxes ever year and the First_year : %2.3f, Second_year: %s, current year %r' %(19.657,'less', 'nothing') )
I have paid taxes ever year and the First_year : 19.657, Second_year: less, current year 'nothing'
Formatting with the .format() method
to do better formatting objects into your string for print statements you can use .format() method
Syntax:
'first_string {} second_string {}' .format('value1','value2')
Example:
>>> print('My name is {}'.format('Feroz'))
My name is Feroz
Other useful methods:
a. Inserted objects can be called by index position
Example:
>>> print('The sequence numbers are {0} {1} {2}'.format ('one', 'two', 'three'))
The sequence numbers are one two three
b. Inserted objects can be assigned by keywords
Example:
>>> print('The sequence numbers are {o} {t} {th}'.format(o='one',t='two',th='three'))
The sequence numbers are one two three
Alignment, padding and precision with .format()
- Left
- Center
- right
By default, the .format() align text to the left, and numbers to the right. However, you can pass an optional <.^, > to set a left, center, and right alignments.
< --- left
^ --- center
> ---- right
Example:
>>> print('{0:<10} | {1:^10} | {2:>10}'.format ('Left', 'Center', 'Right')) , print('{0:<10} | {1:^10} | {2:>10}'.format(11,12,13))
Left | Center | Right
11 | 12 | 13
You can also use the alignment operator with a padding character:
Example:
>>> print('{0:=<10} | {1:+^10} | {2:->10}'.format ('Left', 'Center', 'Right')) , print('{0:*<10} | {1:+^10} | {2:->10}'.format(11,12,13
Left====== | ++Center++ | -----Right
11******** | ++++12++++ | --------13
Field width and Float precision are handled similar way to placeholders.
Exmple:
>>> print('Last year my tax was: %2.3f' %30.896)
Last year my tax was: 30.896
>>> print('Last year my tax was: {0:2.3f}'.format(30.896))
Last year my tax was: 30.896
Formatting String Literals (using f-strings)
This is a new feature introduced in Python 3.6, it offer many other benefits over the older .format() string method.
Example:
>>> name='Feroz'
>>> print(f"My name is {name}.")
My name is Feroz.
>>> print(f"My name is {name!r}.")
My name is 'Feroz'.
Float formatting:
Float formatting syntax:
"result: {value:{width}.{precision}}"
Note: Where as with the .format() method you see that {value:2.2f}, with f-strings this can become {value:{2}.{4}}
Example:
>>> tax=29.123456
>>> print('My last year tax was:{0:2.2f}'.format(tax))
My last year tax was:29.12
>>> print(f"My last year tax was {tax:{2}.{4}}")
My last year tax was 29.12
Note:
With f-strings, precision refers to the total number of digits, not just those following the decimal.This is more closely with scientific notation and statistical analysis.
Additionally, It's important to note that f-strings do not pad to the right of the decimal, even if precision allows it.
>>> tax=29.123456
>>> print('My last year tax was:{0:10.10f}'.format(tax))
My last year tax was:29.1234560000 -------------- padded with 4 decimal points
>>> print(f"My last year tax was {tax:{10}.{10}}")
My last year tax was 29.123456 ----------------- didn't pad though we use decimal size of 10
But, you can over come with that using the below format:
>>> tax=29.123456
>>> print('My last year tax was:{0:10.10f}'.format(tax))
My last year tax was:29.1234560000
>>> print(f"My last year tax was {tax:10.10f}")
My last year tax was 29.1234560000 -------------- This time it padded with 4 decimal points
Difference between int and long data type?
The main difference between int and long is that int is 32 bits in width while long is 64 bits in width.
Comments
Post a Comment