avatarMr. Huseyin

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

22570

Abstract

">def</span> <span class="hljs-title function_">find_Circumference</span>(<span class="hljs-params">radius</span>): <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * math.pi * radius

<span class="hljs-keyword">def</span> <span class="hljs-title function_">find_Area</span>(<span class="hljs-params">radius</span>): <span class="hljs-keyword">return</span> math.pi * radius * radius

r = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">' Please Enter the radius of a circle: '</span>))

diameter = find_Diameter(r) circumference = find_Circumference(r) area = find_Area(r)

<span class="hljs-built_in">print</span>(<span class="hljs-string">"\n Diameter Of a Circle = %.2f"</span> %diameter) <span class="hljs-built_in">print</span>(<span class="hljs-string">" Circumference Of a Circle = %.2f"</span> %circumference) <span class="hljs-built_in">print</span>(<span class="hljs-string">" Area Of a Circle = %.2f"</span> %area)</pre></div><h2 id="a031">25. How to calculate the area of the rectangle, whose width and height are entered using the function on Python?</h2><div id="6191"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">areaRectangle</span>(<span class="hljs-params">a, b</span>): <span class="hljs-keyword">return</span> (a * b)

<span class="hljs-keyword">def</span> <span class="hljs-title function_">perimeterRectangle</span>(<span class="hljs-params">a, b</span>): <span class="hljs-keyword">return</span> (<span class="hljs-number">2</span> * (a + b)) </pre></div><div id="3eeb"><pre>a = 5; b = 6; <span class="hljs-built_in">print</span> (<span class="hljs-string">"Area = "</span>, areaRectangle(a, b))

<span class="hljs-built_in">print</span> (<span class="hljs-string">"Perimeter = "</span>, perimeterRectangle(a, b))</pre></div><h2 id="6064">26. Making a Number Guessing Game with Python</h2><div id="dce4"><pre><span class="hljs-keyword">import</span> random <span class="hljs-keyword">import</span> math</pre></div><div id="a6cb"><pre><span class="hljs-comment"># Taking Inputs</span> lower = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter Lower bound:- "</span>))

<span class="hljs-comment"># Taking Inputs</span> upper = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter Upper bound:- "</span>))

<span class="hljs-comment"># generating random number between</span> <span class="hljs-comment"># the lower and upper</span> x = random.randint(lower, upper) <span class="hljs-built_in">print</span>(<span class="hljs-string">"\n\tYou've only "</span>, <span class="hljs-built_in">round</span>(math.log(upper - lower + <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)), <span class="hljs-string">" chances to guess the integer!\n"</span>)

<span class="hljs-comment"># Initializing the number of guesses.</span> count = <span class="hljs-number">0</span>

<span class="hljs-comment"># for calculation of minimum number of</span> <span class="hljs-comment"># guesses depends upon range</span> <span class="hljs-keyword">while</span> count < math.log(upper - lower + <span class="hljs-number">1</span>, <span class="hljs-number">2</span>): count += <span class="hljs-number">1</span>

<span class="hljs-comment"># taking guessing number as input</span>
guess = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Guess a number:- "</span>))

<span class="hljs-comment"># Condition testing</span>
<span class="hljs-keyword">if</span> x == guess:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"Congratulations you did it in "</span>,
          count, <span class="hljs-string">" try"</span>)
    <span class="hljs-comment"># Once guessed, loop will break</span>
    <span class="hljs-keyword">break</span>
<span class="hljs-keyword">elif</span> x &gt; guess:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"You guessed too small!"</span>)
<span class="hljs-keyword">elif</span> x &lt; guess:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"You Guessed too high!"</span>)

<span class="hljs-comment"># If Guessing is more than required guesses,</span> <span class="hljs-comment"># shows this output.</span> <span class="hljs-keyword">if</span> count >= math.log(upper - lower + <span class="hljs-number">1</span>, <span class="hljs-number">2</span>): <span class="hljs-built_in">print</span>(<span class="hljs-string">"\nThe number is %d"</span> % x) <span class="hljs-built_in">print</span>(<span class="hljs-string">"\tBetter Luck Next time!"</span>)</pre></div><h2 id="d9bd">27. How to find out what day of the year a given date is on Python?</h2><div id="4587"><pre><span class="hljs-variable">import</span> <span class="hljs-variable">datetime</span>

<span class="hljs-variable">date</span>=<span class="hljs-function"><span class="hljs-title">str</span>(<span class="hljs-title">input</span>(<span class="hljs-string">'Enter the date(for example:09 02 2019):'</span>))</span></pre></div><div id="99b8"><pre><span class="hljs-attr">day_name</span>= [<span class="hljs-string">'Monday'</span>, <span class="hljs-string">'Tuesday'</span>, <span class="hljs-string">'Wednesday'</span>, <span class="hljs-string">'Thursday'</span>, <span class="hljs-string">'Friday'</span>, <span class="hljs-string">'Saturday'</span>,<span class="hljs-string">'Sunday'</span>]</pre></div><div id="744b"><pre><span class="hljs-built_in">day</span> = datetime.datetime.strptime(<span class="hljs-built_in">date</span>, <span class="hljs-string">'%d %m %Y'</span>).<span class="hljs-built_in">weekday</span>()</pre></div><div id="37c3"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(day_name[day])</span></span></pre></div><h2 id="6fd7">28. How to find missing numbers in a sorted list range on Python?</h2><div id="c33a"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">find_missing</span>(<span class="hljs-params">lst</span>): <span class="hljs-keyword">return</span> [x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(lst[<span class="hljs-number">0</span>], lst[-<span class="hljs-number">1</span>]+<span class="hljs-number">1</span>)
<span class="hljs-keyword">if</span> x <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> lst]

<span class="hljs-comment"># Driver code </span> lst = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>] <span class="hljs-built_in">print</span>(find_missing(lst))</pre></div><div id="e7a6"><pre>Output: <span class="hljs-string">[3, 5, 8]</span></pre></div><h2 id="0e8f">29. How to check if there is a specified character in a string on Python?</h2><div id="1b58"><pre><span class="hljs-attr">char_list</span> = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span> ,<span class="hljs-string">"c"</span>] <span class="hljs-attr">string</span> = <span class="hljs-string">"abcd"</span></pre></div><div id="34c5"><pre>matched_list = [<span class="hljs-built_in">characters</span> <span class="hljs-keyword">in</span> char_list <span class="hljs-keyword">for</span> <span class="hljs-built_in">characters</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">string</span>]</pre></div><div id="7d80"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(matched_list)</span></span></pre></div><div id="264c"><pre>OUTPUT [<span class="hljs-literal">True</span>, <span class="hljs-literal">True</span>, <span class="hljs-literal">True</span>, <span class="hljs-literal">False</span>]</pre></div><div id="5610"><pre><span class="hljs-attr">string_contains_chars</span> = all(matched_list)</pre></div><div id="7ad0"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(string_contains_chars)</span></span></pre></div><h2 id="582a">30. How to find the average of odd and even averages of whole numbers on Python?</h2><div id="06a1"><pre><span class="hljs-attr">total</span> = <span class="hljs-number">0</span> <span class="hljs-attr">evenSums</span> = <span class="hljs-number">0</span> <span class="hljs-attr">oddSums</span> = <span class="hljs-number">0</span> <span class="hljs-attr">done</span> = <span class="hljs-literal">False</span></pre></div><div id="874b"><pre><span class="hljs-keyword">while</span>(<span class="hljs-keyword">not</span> done): user_in = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Give me an integer or type 'done' to be done."</span>) <span class="hljs-keyword">if</span>( user_in.lower() == <span class="hljs-string">"done"</span>): done = <span class="hljs-literal">True</span> <span class="hljs-keyword">else</span>: <span class="hljs-comment"># assuming they've typed in an integer</span> total += <span class="hljs-built_in">int</span>(user_in) <span class="hljs-keyword">if</span> user_in % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>: evenSums += user_in evenAverage = evenSums / user_in <span class="hljs-keyword">else</span>: oddSums += user_in oddAverage = oddSums / user_in</pre></div><div id="4f37"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(total)</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"Even Average: "</span> + str(evenAverage)</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"Odd Average: "</span> + str(oddAverage)</span></span>)</pre></div><h2 id="0f92">31. How to put records from the database on Python?</h2><div id="78e0"><pre><span class="hljs-keyword">import</span> pymysql.cursors</pre></div><div id="cf69"><pre># <span class="hljs-keyword">Database</span> <span class="hljs-keyword">connection</span> sentence</pre></div><div id="db97"><pre><span class="hljs-attr">connection</span> = pymysql.connect(host=<span class="hljs-string">'localhost'</span>, <span class="hljs-attr">user</span>=<span class="hljs-string">'root'</span>, <span class="hljs-attr">password</span>=<span class="hljs-string">''</span>, <span class="hljs-attr">db</span>=<span class="hljs-string">'students'</span>, <span class="hljs-attr">charset</span>=<span class="hljs-string">'utf8mb4'</span>, <span class="hljs-attr">cursorclass</span>=pymysql.cursors.DictCursor)</pre></div><div id="0cc4"><pre><span class="hljs-keyword">try</span>: with connection.<span class="hljs-built_in">cursor</span>() <span class="hljs-keyword">as</span> <span class="hljs-built_in">cursor</span>:</pre></div><div id="f35c"><pre> # single line reading sql = "<span class="hljs-keyword">SELECT</span> <span class="hljs-symbol">id</span>, <span class="hljs-symbol">firstname</span>,<span class="hljs-symbol">lastname</span> <span class="hljs-keyword">FROM</span> <span class="hljs-symbol">users</span><span class="hljs-string">" cursor.execute(sql)</span></pre></div><div id="6204"><pre> <span class="hljs-keyword">for</span> <span class="hljs-keyword">row</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">cursor</span>.fetchall(): #<span class="hljs-keyword">read</span> <span class="hljs-keyword">all</span> lines firstname = str(<span class="hljs-keyword">row</span>["firstname"]) lastname = str(<span class="hljs-keyword">row</span>["lastname"])</pre></div><div id="504d"><pre> #<span class="hljs-built_in">print</span> on<span class="hljs-built_in"> screen </span> <span class="hljs-built_in">print</span>(<span class="hljs-string">"firstname : "</span> + firstname) <span class="hljs-built_in">print</span>(<span class="hljs-string">"lastname : "</span> + lastname)</pre></div><div id="daaa"><pre><span class="hljs-keyword">finally</span>: connection.<span class="hljs-built_in">close</span>()</pre></div><h2 id="badf">32. How to Use Tkinter Form on Python?</h2><div id="f9c4"><pre><span class="hljs-keyword">from</span> tkinter <span class="hljs-keyword">import</span> * <span class="hljs-keyword">window</span> = Tk()

<span class="hljs-keyword">add</span> widgets here

<span class="hljs-keyword">window</span>.title(<span class="hljs-string">'Hello Python'</span>) <span class="hljs-keyword">window</span>.geometry("300x200+10+20") <span class="hljs-keyword">window</span>.mainloop()</pre></div><h2 id="86c1">33. How to Create Python Form Entry on Python?</h2><div id="278f"><pre><span class="hljs-keyword">from</span> tkinter <span class="hljs-keyword">import</span> * <span class="hljs-keyword">from</span> tkinter <span class="hljs-keyword">import</span> messagebox</pre></div><div id="b505"><pre><span class="hljs-attribute">window</span> <span class="hljs-operator">=</span> Tk()</pre></div><div id="535c"><pre><span class="hljs-keyword">window</span>.<span class="hljs-keyword">title</span>(<span class="hljs-string">"mrhuseyin.medium.com"</span>) <span class="hljs-keyword">window</span>.geometry(<span class="hljs-string">"400x300"</span>)</pre></div><div id="cc8b"><pre><span class="hljs-comment">#plotting grid forms</span> <span class="hljs-attr">application</span> = Frame(window)</pre></div><div id="a83c"><pre>application.grid() L1 = Label(uygulama, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Enter your name"</span>) L1.grid(<span class="hljs-attribute">padx</span>=110, <span class="hljs-attribute">pady</span>=10)</pre></div><div id="f6ae"><pre>E1 = Entry(application, bd =2) E1.grid(<span class="hljs-attribute">padx</span>=110, <span class="hljs-attribute">pady</span>=3)</pre></div><div id="be25"><pre><span class="hljs-selector-id">#draw</span> <span class="hljs-selector-tag">form</span> window<span class="hljs-selector-class">.mainloop</span>()</pre></div><h2 id="8903">34. How to create Python Tkinter ListBox on Python?</h2><div id="00e8"><pre><span class="hljs-keyword">from</span> tkinter <span class="hljs-keyword">import</span> *

<span class="hljs-keyword">from</span> tkinter <span class="hljs-keyword">import</span> messagebox

<span class="hljs-keyword">window</span> = Tk()

<span class="hljs-keyword">window</span>.title("mrhuseyin.medium.com") <span class="hljs-keyword">window</span>.geometry("400x300")

<span class="hljs-meta">#grid form çizdirme</span> application = Frame(<span class="hljs-keyword">window</span>) application.grid()

Lb1 = Listbox(application) Lb1.<span class="hljs-keyword">insert</span>(<span class="hljs-number">1</span>, "Python") Lb1.<span class="hljs-keyword">insert</span>(<span class="hljs-number">2</span>, "C#") Lb1.<span class="hljs-keyword">insert</span>(<span class="hljs-number">3</span>, "JAVA") Lb1.<span class="hljs-keyword">insert</span>(<span class="hljs-number">4</span>, "JAVASCRIPT") Lb1.grid(padx=<span class="hljs-number">110</span>, pady=<span class="hljs-number">10</span>)

<span class="hljs-meta">#draw form</span> pencere.mainloop()</pre></div><h2 id="19d9">35. How to make a simple registration form using Python Tkinter on Python?</h2><div id="0120"><pre><span class="hljs-comment"># import openpyxl and tkinter modules </span> <span class="hljs-keyword">from</span> openpyxl import * <span class="hljs-keyword">from</span> tkinter import *

<span class="hljs-comment"># globally declare wb and sheet variable </span>

<span class="hljs-comment"># opening the existing excel file </span> wb = load_workbook(<span class="hljs-string">'C:\Users\Admin\Desktop\excel.xlsx'</span>)

<span class="hljs-comment"># create the sheet object </span> sheet = wb.active

def excel():

# resize the width of columns <span class="hljs-keyword">in</span> 
# excel spreadsheet 
sheet.column_dimensions[<span class="hljs-string">'A'</span>].width = 30
sheet.column_dimensions[<span class="hljs-string">'B'</span>].width = 10
sheet.column_dimensions[<span class="hljs-string">'C'</span>].width = 10
sheet.column_dimensions[<span class="hljs-string">'D'</span>].width = 20
sheet.column_dimensions[<span class="hljs-string">'E'</span>].width = 20
sheet.column_dimensions[<span class="hljs-string">'F'</span>].width = 40
sheet.column_dimensions[<span class="hljs-string">'G'</span>].width = 50

# write given data <span class="hljs-keyword">to</span> an excel spreadsheet 
# at particular location 
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=1).value = <span class="hljs-string">"Name"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=2).value = <span class="hljs-string">"Course"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=3).value = <span class="hljs-string">"Semester"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=4).value = <span class="hljs-string">"Form Number"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=5).value = <span class="hljs-string">"Contact Number"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=6).value = <span class="hljs-string">"Email id"</span>
sheet.cell(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=7).value = <span class="hljs-string">"Address"</span>

<span class="hljs-comment"># Function to set focus (cursor) </span> def focus1(event): # <span class="hljs-built_in">set</span> focus on the course_field box course_field.focus_set()

<span class="hljs-comment"># Function to set focus </span> def focus2(event): # <span class="hljs-built_in">set</span> focus on the sem_field box sem_field.focus_set()

<span class="hljs-comment"># Function to set focus </span> def focus3(event): # <span class="hljs-built_in">set</span> focus on the form_no_field box form_no_field.focus_set()

<span class="hljs-comment"># Function to set focus </span> def focus4(event): # <span class="hljs-built_in">set</span> focus on the contact_no_field box contact_no_field.focus_set()

<span class="hljs-comment"># Function to set focus </span> def focus5(event): # <span class="hljs-built_in">set</span> focus on the email_id_field box email_id_field.focus_set()

<span class="hljs-comment"># Function to set focus </span> def focus6(event): # <span class="hljs-built_in">set</span> focus on the address_field box address_field.focus_set()

<span class="hljs-comment"># Function for clearing the </span> <span class="hljs-comment"># contents of text entry boxes </span> def clear():

# clear the content of text entry box 
name_field.delete(0, END) 
course_field.delete(0, END) 
sem_field.delete(0, END) 
form_no_field.delete(0, END) 
contact_no_field.delete(0, END) 
email_id_field.delete(0, END) 
address_field.delete(0, END) 

<span class="hljs-comment"># Function to take data from GUI </span> <span class="hljs-comment"># window and write to an excel file </span> def insert():

# <span class="hljs-keyword">if</span><span class="hljs-built_in"> user </span><span class="hljs-keyword">not</span> fill any entry 
# then <span class="hljs-built_in">print</span> <span class="hljs-string">"empty input"</span> 
<span class="hljs-keyword">if</span> (name_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    course_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    sem_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    form_no_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    contact_no_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    email_id_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span> <span class="hljs-keyword">and</span>
    address_field.<span class="hljs-built_in">get</span>() == <span class="hljs-string">""</span>): 
          
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"empty input"</span>) 

<span class="hljs-keyword">else</span>: 

    # assigning the max row <span class="hljs-keyword">and</span> max column 
    # value upto which data is written 
    # <span class="hljs-keyword">in</span> an excel sheet <span class="hljs-keyword">to</span> the variable 
    current_row = sheet.max_row 
    current_column = sheet.max_column 

    # <span class="hljs-built_in">get</span> method returns current text 
    # as string which we write into 
    # excel spreadsheet at particular location 
    sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=1).value = name_field.<span class="hljs-built_in">get</span>() 
    sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=2).value = course_field.<span class="hljs-built_in">get</span>() 
    sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=3).va

Options

lue = sem_field.<span class="hljs-built_in">get</span>() sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=4).value = form_no_field.<span class="hljs-built_in">get</span>() sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=5).value = contact_no_field.<span class="hljs-built_in">get</span>() sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=6).value = email_id_field.<span class="hljs-built_in">get</span>() sheet.cell(<span class="hljs-attribute">row</span>=current_row + 1, <span class="hljs-attribute">column</span>=7).value = address_field.<span class="hljs-built_in">get</span>()

    # save the file 
    wb.save(<span class="hljs-string">'C:\\Users\\Admin\\Desktop\\excel.xlsx'</span>) 

    # <span class="hljs-built_in">set</span> focus on the name_field box 
    name_field.focus_set() 

    # call the clear() function 
    clear() 

<span class="hljs-comment"># Driver code </span> <span class="hljs-keyword">if</span> name == <span class="hljs-string">"main"</span>:

# create a GUI window 
root = Tk() 

# <span class="hljs-built_in">set</span> the background colour of GUI window 
root.configure(<span class="hljs-attribute">background</span>=<span class="hljs-string">'light green'</span>) 

# <span class="hljs-built_in">set</span> the title of GUI window 
root.title(<span class="hljs-string">"registration form"</span>) 

# <span class="hljs-built_in">set</span> the configuration of GUI window 
root.geometry(<span class="hljs-string">"500x300"</span>) 

excel() 

# create a Form label 
heading = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Form"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Name label 
name = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Name"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Course label 
course = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Course"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Semester label 
sem = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Semester"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Form <span class="hljs-literal">No</span>. lable 
form_no = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Form No."</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Contact <span class="hljs-literal">No</span>. label 
contact_no = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Contact No."</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a Email id label 
email_id = Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Email id"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>) 

# create a<span class="hljs-built_in"> address </span>label 

<span class="hljs-built_in"> address </span>= Label(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Address"</span>, <span class="hljs-attribute">bg</span>=<span class="hljs-string">"light green"</span>)

# grid method is used <span class="hljs-keyword">for</span> placing 
# the widgets at respective positions 
# <span class="hljs-keyword">in</span> table like structure . 
heading.grid(<span class="hljs-attribute">row</span>=0, <span class="hljs-attribute">column</span>=1) 
name.grid(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=0) 
course.grid(<span class="hljs-attribute">row</span>=2, <span class="hljs-attribute">column</span>=0) 
sem.grid(<span class="hljs-attribute">row</span>=3, <span class="hljs-attribute">column</span>=0) 
form_no.grid(<span class="hljs-attribute">row</span>=4, <span class="hljs-attribute">column</span>=0) 
contact_no.grid(<span class="hljs-attribute">row</span>=5, <span class="hljs-attribute">column</span>=0) 
email_id.grid(<span class="hljs-attribute">row</span>=6, <span class="hljs-attribute">column</span>=0) 
address.grid(<span class="hljs-attribute">row</span>=7, <span class="hljs-attribute">column</span>=0) 

# create a text entry box 
# <span class="hljs-keyword">for</span> typing the information 
name_field = Entry(root) 
course_field = Entry(root) 
sem_field = Entry(root) 
form_no_field = Entry(root) 
contact_no_field = Entry(root) 
email_id_field = Entry(root) 
address_field = Entry(root) 

# bind method of widget is used <span class="hljs-keyword">for</span> 
# the binding the function with the events 

# whenever the enter key is pressed 
# then call the focus1 function 
name_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus1) 

# whenever the enter key is pressed 
# then call the focus2 function 
course_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus2) 

# whenever the enter key is pressed 
# then call the focus3 function 
sem_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus3) 

# whenever the enter key is pressed 
# then call the focus4 function 
form_no_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus4) 

# whenever the enter key is pressed 
# then call the focus5 function 
contact_no_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus5) 

# whenever the enter key is pressed 
# then call the focus6 function 
email_id_field.bind(<span class="hljs-string">"&lt;Return&gt;"</span>, focus6) 

# grid method is used <span class="hljs-keyword">for</span> placing 
# the widgets at respective positions 
# <span class="hljs-keyword">in</span> table like structure . 
name_field.grid(<span class="hljs-attribute">row</span>=1, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
course_field.grid(<span class="hljs-attribute">row</span>=2, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
sem_field.grid(<span class="hljs-attribute">row</span>=3, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
form_no_field.grid(<span class="hljs-attribute">row</span>=4, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
contact_no_field.grid(<span class="hljs-attribute">row</span>=5, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
email_id_field.grid(<span class="hljs-attribute">row</span>=6, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 
address_field.grid(<span class="hljs-attribute">row</span>=7, <span class="hljs-attribute">column</span>=1, <span class="hljs-attribute">ipadx</span>=<span class="hljs-string">"100"</span>) 

# call excel function 
excel() 

# create a Submit Button <span class="hljs-keyword">and</span> place into the root window 
submit = Button(root, <span class="hljs-attribute">text</span>=<span class="hljs-string">"Submit"</span>, <span class="hljs-attribute">fg</span>=<span class="hljs-string">"Black"</span>, 
                        <span class="hljs-attribute">bg</span>=<span class="hljs-string">"Red"</span>, <span class="hljs-attribute">command</span>=insert) 
submit.grid(<span class="hljs-attribute">row</span>=8, <span class="hljs-attribute">column</span>=1) 

# start the GUI 
root.mainloop()</pre></div><h2 id="08b7">36. How to make a game that guesses the number the user holds on Python?</h2><div id="33ec"><pre><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint

rand = randint(<span class="hljs-number">1</span>, <span class="hljs-number">100</span>) counter = <span class="hljs-number">0</span>

<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: counter+=<span class="hljs-number">1</span> num=<span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter values between 1 and 100 (0 exit):"</span>)) <span class="hljs-keyword">if</span>(num==<span class="hljs-number">0</span>): <span class="hljs-built_in">print</span>(<span class="hljs-string">"You canceled the game."</span>) <span class="hljs-keyword">break</span> <span class="hljs-keyword">elif</span> num < rand: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Enter a Higher Number."</span>) <span class="hljs-keyword">continue</span> <span class="hljs-keyword">elif</span> num > rand: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Enter a Lower Number."</span>) <span class="hljs-keyword">continue</span> <span class="hljs-keyword">else</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Randomly selected number {0}!"</span>.<span class="hljs-built_in">format</span>(rand)) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Your guess number {0}"</span>.<span class="hljs-built_in">format</span>(counter))</pre></div><h2 id="9b80">37. How to make a list of your favorite fruits and print them on the screen on Python?</h2><div id="2796"><pre>favorite_fruits = <span class="hljs-selector-attr">[<span class="hljs-string">'apples'</span>, <span class="hljs-string">'erics'</span>, <span class="hljs-string">'oranges'</span>]</span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"My favourite fruits {}"</span>.format(favorite_fruits)</span></span>)</pre></div><h2 id="4b5c">38. How to print “the number of pi in order, the equivalent of the inch unit in cm, the abbreviation of microprocessors, the name of the operating system you are using” on Python?</h2><div id="4304"><pre><span class="hljs-attribute">list</span>=[<span class="hljs-number">3</span>.<span class="hljs-number">14</span>,<span class="hljs-number">2</span>.<span class="hljs-number">54</span>,<span class="hljs-string">"CPU"</span>,<span class="hljs-string">"WINDOWS 10"</span>]

<span class="hljs-attribute">print</span>(list)</pre></div><div id="0e1b"><pre><span class="hljs-symbol">Output</span>: [<span class="hljs-number">3.14</span>, <span class="hljs-number">2.54</span>, <span class="hljs-string">'CPU'</span>, <span class="hljs-string">'WINDOWS 10'</span>]</pre></div><h2 id="f86e">39. How to make a list of the days of the week beginning with Monday and ending with Friday. Also, how to print the element of the list you have created with an index of 4 on the screen on Python?</h2><div id="3fbd"><pre>weekdays=<span class="hljs-selector-attr">[<span class="hljs-string">"Monday"</span>,<span class="hljs-string">"Tuesday"</span>,<span class="hljs-string">"Wednesday"</span>,<span class="hljs-string">"Thursday"</span>,<span class="hljs-string">"Friday"</span>]</span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(weekdays[<span class="hljs-number">4</span>])</span></span></pre></div><div id="aa80"><pre><span class="hljs-attribute">output Thursday</span></pre></div><h2 id="9c07">40. How to change the list from 3,1,2 values to 1,1,2 respectively on Python?</h2><div id="612c"><pre><span class="hljs-attribute">list</span>=[<span class="hljs-number">3</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>]

<span class="hljs-attribute">list</span>[<span class="hljs-number">0</span>]=<span class="hljs-number">1</span> <span class="hljs-attribute">list</span>[<span class="hljs-number">1</span>]=<span class="hljs-number">1</span> <span class="hljs-attribute">list</span>[<span class="hljs-number">2</span>]=<span class="hljs-number">2</span>

<span class="hljs-attribute">print</span>(list)</pre></div><div id="3acb"><pre>output <span class="hljs-string">[1, 1, 2]</span></pre></div><h2 id="4f70">41. How to make a list of the week’s names and check if some days are on the list on Python?</h2><div id="c281"><pre>weekdays=<span class="hljs-selector-attr">[<span class="hljs-string">"Monday"</span>,<span class="hljs-string">"Tuesday"</span>,<span class="hljs-string">"Wednesday"</span>,<span class="hljs-string">"Thursday"</span>,<span class="hljs-string">"Friday"</span>]</span>

<span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"Friday"</span> in weekdays)</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"Saturday"</span> in weekdays)</span></span></pre></div><div id="d24a"><pre><span class="hljs-built_in">output</span> <span class="hljs-literal">true</span> <span class="hljs-literal">false</span></pre></div><h2 id="0326">42. How to print even numbers in a list on Python?</h2><div id="da33"><pre>list1 = [<span class="hljs-number">10</span>, <span class="hljs-number">21</span>, <span class="hljs-number">4</span>, <span class="hljs-number">45</span>, <span class="hljs-number">66</span>, <span class="hljs-number">93</span>]

<span class="hljs-keyword">for</span> <span class="hljs-built_in">num</span> <span class="hljs-keyword">in</span> list1:

# checking condition 
<span class="hljs-keyword">if</span> <span class="hljs-built_in">num</span> % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>: 
   <span class="hljs-built_in">print</span>(<span class="hljs-built_in">num</span>, end = <span class="hljs-string">" "</span>)</pre></div><h2 id="d2d2">43. Create a list named numbers consisting of 3–18 numbers. Combine the list created with the list of “numbers2 = [21,22,23,24,25]”, then print the numbers divided by 4 on the screen.</h2><div id="adea"><pre>numbers = [<span class="hljs-number">3,4,5,6</span>,<span class="hljs-number">7,8,9,10</span>,<span class="hljs-number">11,12,13,14</span>,<span class="hljs-number">15,16,17,18</span>]

numbers2 = [<span class="hljs-number">21,22,23,24</span>,<span class="hljs-number">25</span>] combine = numbers + numbers2

for number in combine: if sayi%<span class="hljs-number">4</span>==<span class="hljs-number">0</span>: print(number)</pre></div><h2 id="c46a">44. How to write the code with the screen output as below with the while loop on Python?</h2><div id="5c04"><pre><span class="hljs-symbol">1 </span>. class <span class="hljs-symbol">2 </span>. class <span class="hljs-symbol">3 </span>. class <span class="hljs-symbol">4 </span>. class <span class="hljs-symbol">5 </span>. class <span class="hljs-symbol">6 </span>. class <span class="hljs-symbol">7 </span>. class <span class="hljs-symbol">8 </span>. class <span class="hljs-symbol">9 </span>. class <span class="hljs-symbol">10 </span>. class <span class="hljs-symbol">11 </span>. class <span class="hljs-symbol">12 </span>. class</pre></div><div id="7fb7"><pre>Solution<span class="hljs-comment">;</span></pre></div><div id="6703"><pre><span class="hljs-selector-tag">i</span> = <span class="hljs-number">1</span> while <span class="hljs-selector-tag">i</span> <= <span class="hljs-number">12</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">" {}. class"</span><span class="hljs-selector-class">.format</span>(i)) <span class="hljs-selector-tag">i</span> += <span class="hljs-number">1</span></pre></div><h2 id="d19c">45. How to sum the digits of the number the user entered on Python?</h2><div id="b438"><pre>number = <span class="hljs-built_in">input</span>(<span class="hljs-string">"enter a number: "</span>) <span class="hljs-built_in">sum</span>=<span class="hljs-number">0</span> <span class="hljs-keyword">for</span> numberofdigit <span class="hljs-keyword">in</span> number: <span class="hljs-built_in">sum</span> += <span class="hljs-built_in">int</span>(numberofdigit)

<span class="hljs-built_in">print</span>(<span class="hljs-string">"the sum of the digits of the number:"</span>,<span class="hljs-built_in">sum</span>)</pre></div><h2 id="9713">46. How to multiply the digits of the number entered by the user (except zero) on Python?</h2><div id="2fc0"><pre><span class="hljs-variable">number</span> = <span class="hljs-function"><span class="hljs-title">input</span>(<span class="hljs-string">"enter an number: "</span>)</span> <span class="hljs-variable">carpim</span>=<span class="hljs-number">1</span> <span class="hljs-variable">for</span> <span class="hljs-variable">digitofnumber</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-function"><span class="hljs-title">str</span>(<span class="hljs-variable">numaber</span>): <span class="hljs-variable"><span class="hljs-keyword">if</span></span> <span class="hljs-title">int</span>(<span class="hljs-variable">digitofnumber</span>) <span class="hljs-variable">!</span>= <span class="hljs-number">0</span>: <span class="hljs-variable">multiplication</span>*= <span class="hljs-title">int</span>(<span class="hljs-variable">digitofnumber</span>)</span></pre></div><div id="167b"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"digits of the number: "</span>,multiplication)</span></span></pre></div><h2 id="944a">47. How to print the programmer’s name on the screen using the “for loop” on Python?</h2><div id="4bda"><pre><span class="hljs-variable">text</span> = <span class="hljs-function"><span class="hljs-title">input</span>(<span class="hljs-string">"enter a name: "</span>)</span>

<span class="hljs-variable">for</span> <span class="hljs-variable">i</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-function"><span class="hljs-title">range</span>(<span class="hljs-number">10</span>): <span class="hljs-title">print</span>(<span class="hljs-variable">text</span>)</span></pre></div><h2 id="797a">48. How to print the programmer’s name on the screen using the “while loop” on Python?</h2><div id="ab55"><pre><span class="hljs-variable">text</span> = <span class="hljs-function"><span class="hljs-title">input</span>(<span class="hljs-string">"enter a name: "</span>)</span>

<span class="hljs-variable">i</span>=<span class="hljs-number">0</span> <span class="hljs-variable"><span class="hljs-keyword">while</span></span> <span class="hljs-variable">i</span><<span class="hljs-number">10</span>: <span class="hljs-variable">i</span>+=<span class="hljs-number">1</span> <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable">text</span>)</span></pre></div><h2 id="6f32">49. How to find the mean using “sum() and len()” on Python?</h2><div id="ace1"><pre><span class="hljs-attribute">list</span>=[<span class="hljs-number">35</span>,<span class="hljs-number">48</span>,<span class="hljs-number">52</span>,<span class="hljs-number">57</span>,<span class="hljs-number">68</span>,<span class="hljs-number">84</span>]

<span class="hljs-attribute">total</span> = sum(list) <span class="hljs-attribute">piece</span> = len(list)</pre></div><div id="951b"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(total/piece)</span></span></pre></div><h2 id="7b09">50. How to find the sum of numbers until 0 is entered on the keyboard on Python?</h2><div id="f71d"><pre><span class="hljs-keyword">total</span>=0 <span class="hljs-keyword">while</span> True: number = float(<span class="hljs-keyword">input</span>(<span class="hljs-string">"enter a number: "</span>)) <span class="hljs-keyword">if</span> number ==0: <span class="hljs-keyword">break</span> <span class="hljs-keyword">total</span>+=number <span class="hljs-keyword">print</span>(<span class="hljs-string">"The sum of the numbers: "</span>,<span class="hljs-keyword">total</span>)</pre></div><h2 id="affd">51. Python abs example</h2><div id="eda6"><pre><span class="hljs-keyword">number</span> = <span class="hljs-built_in">input</span>(<span class="hljs-string">"enter a number: "</span>) <span class="hljs-keyword">number</span> = <span class="hljs-keyword">int</span>(<span class="hljs-keyword">number</span>) <span class="hljs-keyword">print</span>(<span class="hljs-string">"The absolute value of the number"</span>, <span class="hljs-built_in">abs</span>(<span class="hljs-keyword">number</span>))</pre></div><h2 id="94c1">52. How to calculate absolute value of the number on Python?</h2><div id="4e53"><pre><span class="hljs-keyword">number</span> = <span class="hljs-built_in">input</span>(<span class="hljs-string">"enter an number: "</span>) <span class="hljs-keyword">number</span> = <span class="hljs-keyword">int</span>(<span class="hljs-keyword">number</span>) <span class="hljs-keyword">if</span> <span class="hljs-keyword">number</span><<span class="hljs-number">0</span>: <span class="hljs-keyword">number</span>*=-<span class="hljs-number">1</span> <span class="hljs-keyword">print</span>(<span class="hljs-string">"The absolute value of the number: "</span>,<span class="hljs-keyword">number</span>)</pre></div><p id="2003">I hope these can help you..</p><p id="6d4d">Source: <a href="https://www.tutsmake.com/">1</a> <a href="https://www.tutorialgateway.org/">2</a> <a href="https://www.geeksforgeeks.org/">3</a> <a href="https://stackoverflow.com/">4</a> <a href="https://www.yazilimkodlama.com/">5</a> <a href="https://pythonbasics.org/">6</a> <a href="https://www.tutorialsteacher.com/">7</a></p></article></body>

50+ Basic Python Code Examples

List, strings, score calculation and more..

Image by Author

1. How to print “Hello World” on Python?

print("Hello World")

2. How to print “Hello + Username” with the user’s name on Python?

usertext = input("What is your name? ")
print("Hello", usertext)

3. How to add 2 numbers entered on Python?

num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

sum = float(num1) + float(num2)

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

4. How to find the Average of 2 Entered Numbers on Python?

num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

average =(int(num1) + int(num2))

print('average:{0} '.format(average))

5. How to calculate the Entered Visa and Final Grade Average on Python?

visagrade = input('enter your visa grade : ')
finalgrade = input('enter your final grade : ')
average =(float(visagrade)*0.3)+(float(finalgrade)*0.7)
print("average :{0} ".format(average))

6. How to find the Average of 3 Written Grades entered on Python?

firstexam = input('your first exam : ')
secondexam = input('your second exam : ')
thirdexam = input('your third exam : ')
average =(float(firstexam)+float(secondexam)+float(thirdexam))/3
print("average :{0} ".format(average))

7. How to show the Class Pass Status (PASSED — FAILED) of the Student whose Written Average Has Been Entered on Python?

average = input('enter average : ')
if(int(ort)>=50):
print("Passed")
else:
print("Failed")

8. How to find out if the entered number is odd or even on Python?

num = int(input("Enter a number: "))
if (num % 2) == 0:
   print("{0} is Even".format(num))
else:
   print("{0} is Odd".format(num))

9. How to find out if the entered number is Positive, Negative, or 0 on Python?

num = float(input("Enter a number: "))
if num > 0:
   print("Positive number")
elif num == 0:
   print("Zero")
else:
   print("Negative number")

10. How to calculate body mass index on Python?

print("body mass index calculation program")
height = float(input("enter height (m):"))
weight = int(input("enter weight (kg):"))
 
index  = weight/(height*height)
 
if index <=18:
    print("\n underweight BMİ:{}".format(index))
elif index > 18 and index <=25 :
    print("\n overweight BMİ:{}".format(index))
elif index > 25 and index <=30:
    print("\n obese BMİ:{}".format(index))
elif index > 30:
    print("\n severely obese BMİ:{}".format(index))

11. How to show if the person whose age is entered can get a driver’s license on Python?

age = input('enter age : ')
if(int(age)<18):
print("Your Age Is Not Eligible To Get A Driver's License")
else:
print("Your Age Is Eligible To Get Your License")

12. How to List Numbers 1–100 on the Screen on Python?

for i in range(1,101):
print(i)

13. How to List Even Numbers 1–100 on Python?

for i in range(1,101):
if i%2==0:
print(i)

14. How to List Odd Numbers from 1–100 on Python?

for i in range(1,101):
if i%2!=0:
print(i)

15. How to find numbers between 1 and 100 that are divided by 3 and 5 on Python?

for i in range(1,101):
if i%3==0 or i%5==0:
print(i)

16. How to list Numbers from 1 to User-Entered Number on Python?

num = input('enter number : ')
for i in range(1,int(num)+1):
print(i)

17. How to find the Area and Perimeter of a Rectangle With Its Sides on Python?

short = input('Enter short side : ')
tall = input('Enter tall side : ')
area = int(short)*int(tall)
perimeter =2*(int(short)+int(tall))
print("area: {0}".format(alan))
print("perimeter: {0}".format(cevre))

18. How to print the letters of the entered text one under the other on Python?

word = 'mrhuseyin'
for char in word:
    print(char)

19. How to show the sum of numbers between two numbers the user has entered on Python?

sumofnumbers=0;
num1 = input('first number: ')
num2 = input('second number: ')
for i in range(int(sayi1)+1,int(sayi2)):
sumofnumbers+=i
print("Sum of numbers between {0} and {1} : {2}".format(num1,num2,sumofnumbers))

20. For example, let’s ask the user about their choice of cinema or theater. You have to pay 10 dollars to watch movies and 5 dollars for theater. We think that students get 50% discount. If the student is discounted; If he is not a student, let’s write a document that calculates the non-discounted amount and prints it.

selection = input("Press (1) for Cinema, (2) for Theater : ")
student = input("Are you student(Y/N) : ")
price = 0
#non-discounted fee calculation
if selection == '1':
price = 10 #cinema
elif selection == '2':
price = 5 #theatre
#student discount
if student =='Y' or student =='y':
price=price / 2  #%50
print(" The fee you have to pay :{}".format(price))

21. How to find out if the entered number is Prime or Not on Python?

num = int(input("Enter a number: "))  
  
if num > 1:  
   for i in range(2,num):  
       if (num % i) == 0:  
           print(num,"is not a prime number")  
           print(i,"times",num//i,"is",num)  
           break  
   else:  
       print(num,"is a prime number")  
         
else:  
   print(num,"is not a prime number")

22. How to separately find the sum of odd and even numbers up to the number that the user has entered on Python?

NumList = []
Even_Sum = 0
Odd_Sum = 0

Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    NumList.append(value)

for j in range(Number):
    if(NumList[j] % 2 == 0):
        Even_Sum = Even_Sum + NumList[j]
    else:
        Odd_Sum = Odd_Sum + NumList[j]

print("\nThe Sum of Even Numbers in this List =  ", Even_Sum)
print("The Sum of Odd Numbers in this List =  ", Odd_Sum)

23. How to calculate the increased salary of the worker whose salary and raise rate is entered on Python?

newsalary = 0
salary = input("enter new salary : ")
raise = input("salary raise rate(%) : ")
newsalary = int(salary)+(int(salary)*int(raise)/100)
print("increased salary :",newsalary)

24. How to calculate the area and circumference of the circle whose radius is entered using the function on Python?

import math
 
def find_Diameter(radius):
    return 2 * radius
 
def find_Circumference(radius):
    return 2 * math.pi * radius
 
def find_Area(radius):
    return math.pi * radius * radius
 
r = float(input(' Please Enter the radius of a circle: '))
 
diameter = find_Diameter(r)
circumference = find_Circumference(r)
area = find_Area(r)
 
print("\n Diameter Of a Circle = %.2f" %diameter)
print(" Circumference Of a Circle = %.2f" %circumference)
print(" Area Of a Circle = %.2f" %area)

25. How to calculate the area of the rectangle, whose width and height are entered using the function on Python?

def areaRectangle(a, b): 
    return (a * b) 
  
def perimeterRectangle(a, b): 
    return (2 * (a + b)) 
a = 5; 
b = 6; print ("Area = ", areaRectangle(a, b))

print ("Perimeter = ", perimeterRectangle(a, b))

26. Making a Number Guessing Game with Python

import random
import math
# Taking Inputs
lower = int(input("Enter Lower bound:- "))
 
# Taking Inputs
upper = int(input("Enter Upper bound:- "))
 
# generating random number between
# the lower and upper
x = random.randint(lower, upper)
print("\n\tYou've only ", 
       round(math.log(upper - lower + 1, 2)),
      " chances to guess the integer!\n")
 
# Initializing the number of guesses.
count = 0
 
# for calculation of minimum number of
# guesses depends upon range
while count < math.log(upper - lower + 1, 2):
    count += 1
 
    # taking guessing number as input
    guess = int(input("Guess a number:- "))
 
    # Condition testing
    if x == guess:
        print("Congratulations you did it in ",
              count, " try")
        # Once guessed, loop will break
        break
    elif x > guess:
        print("You guessed too small!")
    elif x < guess:
        print("You Guessed too high!")
 
# If Guessing is more than required guesses,
# shows this output.
if count >= math.log(upper - lower + 1, 2):
    print("\nThe number is %d" % x)
    print("\tBetter Luck Next time!")

27. How to find out what day of the year a given date is on Python?

import datetime

date=str(input('Enter the date(for example:09 02 2019):'))
day_name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday']
day = datetime.datetime.strptime(date, '%d %m %Y').weekday()
print(day_name[day])

28. How to find missing numbers in a sorted list range on Python?

def find_missing(lst): 
    return [x for x in range(lst[0], lst[-1]+1)  
                               if x not in lst] 
  
# Driver code 
lst = [1, 2, 4, 6, 7, 9, 10] 
print(find_missing(lst))
Output:
[3, 5, 8]

29. How to check if there is a specified character in a string on Python?

char_list = ["a", "b" ,"c"]
string = "abcd"
matched_list = [characters in char_list for characters in string]
print(matched_list)
OUTPUT
[True, True, True, False]
string_contains_chars = all(matched_list)
print(string_contains_chars)

30. How to find the average of odd and even averages of whole numbers on Python?

total = 0
evenSums = 0
oddSums = 0
done = False
while(not done):
    user_in = input("Give me an integer or type 'done' to be done.")
    if( user_in.lower() == "done"):
        done = True
    else:
        # assuming they've typed in an integer
        total += int(user_in)
        if user_in % 2 == 0:
            evenSums += user_in
            evenAverage = evenSums / user_in
        else:
            oddSums += user_in
            oddAverage = oddSums / user_in
print(total)
print("Even Average: " + str(evenAverage))
print("Odd Average: " + str(oddAverage))

31. How to put records from the database on Python?

import pymysql.cursors
# Database connection sentence
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='students',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
try:
    with connection.cursor() as cursor:
        # single line reading
        sql = "SELECT `id`, `firstname`,`lastname` FROM `users`"
        cursor.execute(sql)
        for row in cursor.fetchall():
            #read all lines
            firstname = str(row["firstname"])
            lastname = str(row["lastname"])
            #print on screen
             print("firstname : " + firstname)
             print("lastname : " + lastname)
finally:
        connection.close()

32. How to Use Tkinter Form on Python?

from tkinter import *
window = Tk()
# add widgets here

window.title('Hello Python')
window.geometry("300x200+10+20")
window.mainloop()

33. How to Create Python Form Entry on Python?

from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("mrhuseyin.medium.com")
window.geometry("400x300")
#plotting grid forms
application = Frame(window)
application.grid()
L1 = Label(uygulama, text="Enter your name")
L1.grid(padx=110, pady=10)
E1 = Entry(application, bd =2)
E1.grid(padx=110, pady=3)
#draw form
window.mainloop()

34. How to create Python Tkinter ListBox on Python?

from tkinter import *
 
from tkinter import messagebox
 
window = Tk()
 
window.title("mrhuseyin.medium.com")
window.geometry("400x300")
 
#grid form çizdirme
application = Frame(window)
application.grid()
 
 
Lb1 = Listbox(application)
Lb1.insert(1, "Python")
Lb1.insert(2, "C#")
Lb1.insert(3, "JAVA")
Lb1.insert(4, "JAVASCRIPT")
Lb1.grid(padx=110, pady=10)
 
#draw form
pencere.mainloop()

35. How to make a simple registration form using Python Tkinter on Python?

# import openpyxl and tkinter modules 
from openpyxl import *
from tkinter import *
  
# globally declare wb and sheet variable 
  
# opening the existing excel file 
wb = load_workbook('C:\\Users\\Admin\\Desktop\\excel.xlsx') 
  
# create the sheet object 
sheet = wb.active 
  
  
def excel(): 
      
    # resize the width of columns in 
    # excel spreadsheet 
    sheet.column_dimensions['A'].width = 30
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 20
    sheet.column_dimensions['E'].width = 20
    sheet.column_dimensions['F'].width = 40
    sheet.column_dimensions['G'].width = 50
  
    # write given data to an excel spreadsheet 
    # at particular location 
    sheet.cell(row=1, column=1).value = "Name"
    sheet.cell(row=1, column=2).value = "Course"
    sheet.cell(row=1, column=3).value = "Semester"
    sheet.cell(row=1, column=4).value = "Form Number"
    sheet.cell(row=1, column=5).value = "Contact Number"
    sheet.cell(row=1, column=6).value = "Email id"
    sheet.cell(row=1, column=7).value = "Address"
  
  
# Function to set focus (cursor) 
def focus1(event): 
    # set focus on the course_field box 
    course_field.focus_set() 
  
  
# Function to set focus 
def focus2(event): 
    # set focus on the sem_field box 
    sem_field.focus_set() 
  
  
# Function to set focus 
def focus3(event): 
    # set focus on the form_no_field box 
    form_no_field.focus_set() 
  
  
# Function to set focus 
def focus4(event): 
    # set focus on the contact_no_field box 
    contact_no_field.focus_set() 
  
  
# Function to set focus 
def focus5(event): 
    # set focus on the email_id_field box 
    email_id_field.focus_set() 
  
  
# Function to set focus 
def focus6(event): 
    # set focus on the address_field box 
    address_field.focus_set() 
  
  
# Function for clearing the 
# contents of text entry boxes 
def clear(): 
      
    # clear the content of text entry box 
    name_field.delete(0, END) 
    course_field.delete(0, END) 
    sem_field.delete(0, END) 
    form_no_field.delete(0, END) 
    contact_no_field.delete(0, END) 
    email_id_field.delete(0, END) 
    address_field.delete(0, END) 
  
  
# Function to take data from GUI  
# window and write to an excel file 
def insert(): 
      
    # if user not fill any entry 
    # then print "empty input" 
    if (name_field.get() == "" and
        course_field.get() == "" and
        sem_field.get() == "" and
        form_no_field.get() == "" and
        contact_no_field.get() == "" and
        email_id_field.get() == "" and
        address_field.get() == ""): 
              
        print("empty input") 
  
    else: 
  
        # assigning the max row and max column 
        # value upto which data is written 
        # in an excel sheet to the variable 
        current_row = sheet.max_row 
        current_column = sheet.max_column 
  
        # get method returns current text 
        # as string which we write into 
        # excel spreadsheet at particular location 
        sheet.cell(row=current_row + 1, column=1).value = name_field.get() 
        sheet.cell(row=current_row + 1, column=2).value = course_field.get() 
        sheet.cell(row=current_row + 1, column=3).value = sem_field.get() 
        sheet.cell(row=current_row + 1, column=4).value = form_no_field.get() 
        sheet.cell(row=current_row + 1, column=5).value = contact_no_field.get() 
        sheet.cell(row=current_row + 1, column=6).value = email_id_field.get() 
        sheet.cell(row=current_row + 1, column=7).value = address_field.get() 
  
        # save the file 
        wb.save('C:\\Users\\Admin\\Desktop\\excel.xlsx') 
  
        # set focus on the name_field box 
        name_field.focus_set() 
  
        # call the clear() function 
        clear() 
  
  
# Driver code 
if __name__ == "__main__": 
      
    # create a GUI window 
    root = Tk() 
  
    # set the background colour of GUI window 
    root.configure(background='light green') 
  
    # set the title of GUI window 
    root.title("registration form") 
  
    # set the configuration of GUI window 
    root.geometry("500x300") 
  
    excel() 
  
    # create a Form label 
    heading = Label(root, text="Form", bg="light green") 
  
    # create a Name label 
    name = Label(root, text="Name", bg="light green") 
  
    # create a Course label 
    course = Label(root, text="Course", bg="light green") 
  
    # create a Semester label 
    sem = Label(root, text="Semester", bg="light green") 
  
    # create a Form No. lable 
    form_no = Label(root, text="Form No.", bg="light green") 
  
    # create a Contact No. label 
    contact_no = Label(root, text="Contact No.", bg="light green") 
  
    # create a Email id label 
    email_id = Label(root, text="Email id", bg="light green") 
  
    # create a address label 
    address = Label(root, text="Address", bg="light green") 
  
    # grid method is used for placing 
    # the widgets at respective positions 
    # in table like structure . 
    heading.grid(row=0, column=1) 
    name.grid(row=1, column=0) 
    course.grid(row=2, column=0) 
    sem.grid(row=3, column=0) 
    form_no.grid(row=4, column=0) 
    contact_no.grid(row=5, column=0) 
    email_id.grid(row=6, column=0) 
    address.grid(row=7, column=0) 
  
    # create a text entry box 
    # for typing the information 
    name_field = Entry(root) 
    course_field = Entry(root) 
    sem_field = Entry(root) 
    form_no_field = Entry(root) 
    contact_no_field = Entry(root) 
    email_id_field = Entry(root) 
    address_field = Entry(root) 
  
    # bind method of widget is used for 
    # the binding the function with the events 
  
    # whenever the enter key is pressed 
    # then call the focus1 function 
    name_field.bind("<Return>", focus1) 
  
    # whenever the enter key is pressed 
    # then call the focus2 function 
    course_field.bind("<Return>", focus2) 
  
    # whenever the enter key is pressed 
    # then call the focus3 function 
    sem_field.bind("<Return>", focus3) 
  
    # whenever the enter key is pressed 
    # then call the focus4 function 
    form_no_field.bind("<Return>", focus4) 
  
    # whenever the enter key is pressed 
    # then call the focus5 function 
    contact_no_field.bind("<Return>", focus5) 
  
    # whenever the enter key is pressed 
    # then call the focus6 function 
    email_id_field.bind("<Return>", focus6) 
  
    # grid method is used for placing 
    # the widgets at respective positions 
    # in table like structure . 
    name_field.grid(row=1, column=1, ipadx="100") 
    course_field.grid(row=2, column=1, ipadx="100") 
    sem_field.grid(row=3, column=1, ipadx="100") 
    form_no_field.grid(row=4, column=1, ipadx="100") 
    contact_no_field.grid(row=5, column=1, ipadx="100") 
    email_id_field.grid(row=6, column=1, ipadx="100") 
    address_field.grid(row=7, column=1, ipadx="100") 
  
    # call excel function 
    excel() 
  
    # create a Submit Button and place into the root window 
    submit = Button(root, text="Submit", fg="Black", 
                            bg="Red", command=insert) 
    submit.grid(row=8, column=1) 
  
    # start the GUI 
    root.mainloop()

36. How to make a game that guesses the number the user holds on Python?

from random import randint
 
rand = randint(1, 100)
counter = 0
 
while True:
    counter+=1
    num=int(input("Enter values between 1 and 100 (0 exit):"))
    if(num==0):
        print("You canceled the game.")
        break
    elif num < rand:
        print("Enter a Higher Number.")
        continue
    elif num > rand:
        print("Enter a Lower Number.")
        continue
    else:
        print("Randomly selected number {0}!".format(rand))
        print("Your guess number {0}".format(counter))

37. How to make a list of your favorite fruits and print them on the screen on Python?

favorite_fruits = ['apples', 'erics', 'oranges']
print("My favourite fruits {}".format(favorite_fruits))

38. How to print “the number of pi in order, the equivalent of the inch unit in cm, the abbreviation of microprocessors, the name of the operating system you are using” on Python?

list=[3.14,2.54,"CPU","WINDOWS 10"]
 
print(list)
Output:
[3.14, 2.54, 'CPU', 'WINDOWS 10']

39. How to make a list of the days of the week beginning with Monday and ending with Friday. Also, how to print the element of the list you have created with an index of 4 on the screen on Python?

weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday"]
print(weekdays[4])
output
Thursday

40. How to change the list from 3,1,2 values to 1,1,2 respectively on Python?

list=[3,1,2]
 
list[0]=1
list[1]=1
list[2]=2
 
print(list)
output
[1, 1, 2]

41. How to make a list of the week’s names and check if some days are on the list on Python?

weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday"]
 
print("Friday" in weekdays)
print("Saturday" in weekdays)
output
true
false

42. How to print even numbers in a list on Python?

list1 = [10, 21, 4, 45, 66, 93] 
  
for num in list1: 
      
    # checking condition 
    if num % 2 == 0: 
       print(num, end = " ")

43. Create a list named numbers consisting of 3–18 numbers. Combine the list created with the list of “numbers2 = [21,22,23,24,25]”, then print the numbers divided by 4 on the screen.

numbers = [3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
numbers2 = [21,22,23,24,25]
combine = numbers + numbers2
 
for number in combine:
 if sayi%4==0:
  print(number)

44. How to write the code with the screen output as below with the while loop on Python?

1 . class
2 . class
3 . class
4 . class
5 . class
6 . class
7 . class
8 . class
9 . class
10 . class
11 . class
12 . class
Solution;
i = 1
while i <= 12:
  print(" {}. class".format(i))
  i += 1

45. How to sum the digits of the number the user entered on Python?

number = input("enter a number: ")
sum=0
for numberofdigit in number:
  sum += int(numberofdigit)
 
print("the sum of the digits of the number:",sum)

46. How to multiply the digits of the number entered by the user (except zero) on Python?

number = input("enter an number: ")
carpim=1
for digitofnumber in str(numaber):
  if int(digitofnumber) != 0:
    multiplication*= int(digitofnumber)
print("digits of the number: ",multiplication)

47. How to print the programmer’s name on the screen using the “for loop” on Python?

text = input("enter a name: ")
 
for i in range(10):
  print(text)

48. How to print the programmer’s name on the screen using the “while loop” on Python?

text = input("enter a name: ")
 
i=0
while i<10:
  i+=1
  print(text)

49. How to find the mean using “sum() and len()” on Python?

list=[35,48,52,57,68,84]
 
total = sum(list)
piece = len(list)
print(total/piece)

50. How to find the sum of numbers until 0 is entered on the keyboard on Python?

total=0
while True:
  number = float(input("enter a number: "))
  if number ==0:
    break
  total+=number
print("The sum of the numbers: ",total)

51. Python abs example

number = input("enter a number: ") 
number = int(number) 
print("The absolute value of the number", abs(number))

52. How to calculate absolute value of the number on Python?

number = input("enter an number: ")
number = int(number)
if number<0:
  number*=-1
print("The absolute value of the number: ",number)

I hope these can help you..

Source: 1 2 3 4 5 6 7

Software Development
Programming
Coding
Python
Machine Learning
Recommended from ReadMedium